62,040
社区成员
发帖
与我相关
我的任务
分享
GET http://10.10.134.63:9002/api/Account/UserInfo HTTP/1.1
Host: 10.10.134.63:9002
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; rv:32.0) Gecko/20100101 Firefox/32.0
Accept: */*
Authorization: Bearer u3kZgQLUbMn2wX0JPF4Os75qi2XugVcNUR5k_p
Authorization: Bearer YOUR_ACCESS_TOKEN
官方文档:http://www.asp.net/web-api/overview/security/individual-accounts-in-web-api
// Configure the application for OAuth based flow
PublicClientId = "self";
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/Token"),
Provider = new ApplicationOAuthProvider(PublicClientId),
AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
AllowInsecureHttp = true
};
// Enable the application to use bearer tokens to authenticate users
app.UseOAuthBearerTokens(OAuthOptions);
2, $\Providers\ApplicationOAuthProvider.cs
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
OAuthDefaults.AuthenticationType);
ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
CookieAuthenticationDefaults.AuthenticationType);
AuthenticationProperties properties = CreateProperties(user.UserName);
AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
context.Validated(ticket);
context.Request.Context.Authentication.SignIn(cookiesIdentity);
}
3. register api:
POST api/Account/Register
{
"Email": "sample string 1",
"Password": "sample string 2",
"ConfirmPassword": "sample string 3"
}
4. post /token
POST /Token
Content-Type: application/x-www-form-urlencoded
body: grant_type=password&username=uname&password=pwd
具体的返回值你可以看一下response。里面有token,再访问values的时候带上。
{"access_token":"u3kZgQLUbMn2wX0JPF4Os75qi2XugVcNUR5k_pB95sx4WEGvPlsr1t6TLxgmJYna9KGU1hY1AFUvImALMu8dn_ZhB38-ylJMkcjGeR6Z6W0drrP434ey3terVoQfCGo7af5BVQCKX-6Q6dTSNeGEqn7PPfzcUhV1MRN9z3mb_epg3EI3HUTUP1MfvQPNUU_CtdGpOlMKFCHYRvCJwV_l-3cUJrIQnlctQQC895LDWHLtTawkfmOvHf3B1NI7I6Wg8s3R8Yanf6bmLRw4-oeezTnaWDlKsF5kwNIGwI-kfcsJ7bK6BHMNqMfL8EFznYFcmhfbUyiL1fS6xMEQ0BxCzkewPDSvNYZtkE_eiCyjrJIwKmAyG4TBW5gWJEEG6HLro_6nDSWTFWpVQc9VzMspXObsdsXI2y3onLr2lR6UnOpDEs6wQQ-JmHfTZdoeW73iWoyL7gtOMoLyAXAfSmCCYykzwSAOifmcTVYT6iLOY3I","token_type":"bearer","expires_in":1209599,"userName":"810156785@qq.com",".issued":"Tue, 12 Jul 2016 05:36:00 GMT",".expires":"Tue, 26 Jul 2016 05:36:00 GMT"}
然后复制token的值到http://10.10.134.63:9002/api/Account/UserInfo?token=获取到的access_token url中,其中api/Account/UserInfo是get方式的,按理说我得到token后再每个api后面加上我的token 就是有权访问该接口了,但是按照上面说的去访问我的接口的时候还是提示“已拒绝为此请求授权”!