问题描述
我正在使用IdentityServer4在我的ASP.NET核心API中处理身份验证和授权.我在客户端使用angular4.我知道我可以使用令牌终结点( http://myapidomain/connect/token )通过以下方式获取access_token
使用grantype = ResourceOwnerPassword
.这意味着我在登录UI中提供了username
和password
进行身份验证.
I'm using IdentityServer4 to handle authentication and authorization in my ASP.NET core API. I use angular4 on client side.I know that I can use token endpoint (http://myapidomain/connect/token) to get access_token
by using grantype = ResourceOwnerPassword
. It means that I provide username
and password
in login UI to authenticate.
我的问题是:我们是否需要再实现API Account/Login
?我认为IdentityServer4已经通过cookie身份验证中间件自动处理登录.如果我们需要实现API Account/Login
.实施该方法的最佳实践是什么.我在某处读到的是使用它进行登录
My question is: do we need to implement API Account/Login
anymore? I think that IdentityServer4 is already handle signin via cookie authentication middleware automatically.If we need to implement API Account/Login
. What is best practice to implement that.I read somewhere is that use this for login
await HttpContext.Authentication.SignInAsync(identityUser.Id, identityUser.UserName);
这是要注销的
await HttpContext.Authentication.SignOutAsync
我的第二个问题是:当我从connect/token
获得access_token
时.我尝试通过访问 http://myapidomain/connect/userinfo 获取userinfo.但是我总是得到405错误代码.我想念的是什么
The second question of mine is:When I get access_token
from connect/token
. I try to get userinfo by access http://myapidomain/connect/userinfo. But I always get 405 error code.What are my missing
在角度客户端
authFormHeaders() {
const header = new Headers();
header.append('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8');
header.append('Accept', 'application/json');
header.append('Authorization', 'Bearer ' + this.oidcSecurityCommon.getAccessToken());
return header;
}
getUserInfo() {
let self = this;
let options = new RequestOptions({
method: RequestMethod.Get,
headers: this.authService.authFormHeaders()
});
return self.http.get(this.authWellKnownEndpoints.userinfoEndpoint, options)
.map((res: Response) => {
return res.json();
})
.catch(self.appService.handleError);
}
在我的API服务器端:
in my API server side:
CorsPolicyBuilder corsBuilder = new CorsPolicyBuilder()
.AllowAnyHeader()
.AllowAnyMethod()
.AllowAnyOrigin()
.AllowCredentials();
services.AddCors(opts =>
{
opts.AddPolicy("AllowAllOrigins", corsBuilder.Build());
});
var url = optionsAccessor.Value.SystemConfig.Authority;
app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
{
Authority = url,
RequireHttpsMetadata = false,
ApiName = "netpower.qms.saas.api"/*,
AllowedScopes = { IdentityServerConstants.StandardScopes.OpenId }*/
});
app.UseCors("AllowAllOrigins");
推荐答案
对于Angular客户端,您应该使用隐含,而不是 ResourceOwnerPassword .资源所有者密码凭据授予类型适用于资源所有者与客户端(例如设备)具有信任关系的情况操作系统或特权较高的应用程序.授权服务器在启用此授予类型时应格外小心,并且仅在其他流程不可行时才允许它(来自OAuth 规范)
For Angular client, should you be using grantype Implicit and not ResourceOwnerPassword.The resource owner password credentials grant type is suitable in cases where the resource owner has a trust relationship with the client, such as the device operating system or a highly privileged application.The authorization server should take special care when enabling this grant type and only allow it when other flows are not viable(From OAuth Spec)
要使用隐式实现,您可以参考此,并且要使用ResourceOwnerpassword,请参考此.
For implementation using Implicit,you can refer this and for using ResourceOwnerpassword ,refer this .
资源类型的流程如下
+----------+
| Resource |
| Owner |
| |
+----------+
v
| Resource Owner
(A) Password Credentials
|
v
+---------+ +---------------+
| |>--(B)---- Resource Owner ------->| |
| | Password Credentials | Authorization |
| Client | | Server |
| |<--(C)---- Access Token ---------<| |
| | (w/ Optional Refresh Token) | |
+---------+ +---------------+
对于Angular和Identity Server 4的ResourceOwnerPassword类型,可以引用此 GitHub存储库,其中还包含一些用于客户端和服务器端的示例代码
For ResourceOwnerPassword type with Angular and Identity Server 4,You can refer this GitHub repo which also contains some sample code for client and server side
步骤如下
-
资源所有者向客户端提供其用户名和 密码.
The resource owner provides the client with its username and password.
客户端从授权请求访问令牌 服务器的令牌端点(包括收到的凭据) 来自资源所有者.提出要求时,客户 通过授权服务器进行身份验证.
The client requests an access token from the authorization server's token endpoint by including the credentials received from the resource owner. When making the request, the client authenticates with the authorization server.
授权服务器对客户端进行身份验证并验证 资源所有者凭证,如果有效,则发出访问权限 令牌.
The authorization server authenticates the client and validates the resource owner credentials, and if valid, issues an access token.
我们是否需要再实现API帐户/登录?
否,您不必实施.您怀疑这是在授权服务器中完成的.您会将用户名和密码发送到Identity Server 4身份验证服务器,这将为您提供Bearer令牌.以及您的中间件(app.UseIdentityServerAuthentication
)将对您的应用程序的请求进行身份验证.
No you do not have to implement.As you suspected,this is done in the Authorization Server.You will send the user name and password to Identity Server 4 Authentication Server and that will be giving you the Bearer token.And your middleware (app.UseIdentityServerAuthentication
) will authenticate the request for your application .
我尝试通过访问 http://myapidomain/connect/userinfo 获取用户信息.但是我总是得到405错误代码.我想念的是什么
I try to get userinfo by access http://myapidomain/connect/userinfo. But I always get 405 error code. What are my missing
您可以查看身份服务器日志以查找丢失的内容.我捕获了一个示例请求,它看起来像这样
You can look into identity server logs to find out what is missing.I captured a sample requests and it will look like this
POST http://myapidomain/connect/token HTTP/1.1
Host: myapidomain
Proxy-Connection: keep-alive
Content-Length: 142
Pragma: no-cache
Cache-Control: no-cache
Accept: application/json, text/plain, */*
Origin: http://angularspawebapi.azurewebsites.net
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.110 Safari/537.36
Content-Type: application/x-www-form-urlencoded
client_id=AngularSPA&grant_type=password&username=admin%40gmail.com&password=Admin01*&scope=WebAPI%20offline_access%20openid%20profile%20roles
GET http://myapidomain/connect/userinfo HTTP/1.1
Host: myapidomain
Proxy-Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
Accept: application/json, text/plain, */*
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.110 Safari/537.36
Authorization: Bearer eyJhbGciOiJSUzI1NiIsImtpZCI6IjhDRTQ1ODAwQTAwNkExNkZGMzEwOTExMDVCRjNDNTY2MzgzNEUxQkEiLCJ0eXAiOiJKV1QiLCJ4NXQiOiJqT1JZQUtBR29XX3pFSkVRV19QRlpqZzA0Ym8ifQ.eyJuYmYiOjE1MDAwOTk4NjIsImV4cCI6MTUwMDEwMDc2MiwiaXNzIjoiaHR0cDovL2FuZ3VsYXJzcGF3ZWJhcGkuYXp1cmV3ZWJzaXRlcy5uZXQiLCJhdWQiOlsiaHR0cDovL2FuZ3VsYXJzcGF3ZWJhcGkuYXp1cmV3ZWJzaXRlcy5uZXQvcmVzb3VyY2VzIiwiV2ViQVBJIl0sImNsaWVudF9pZCI6IkFuZ3VsYXJTUEEiLCJzdWIiOiI5Y2I1ZGViNS1iZWRmLTRkMWItOThkNS05ZTFjYTgwNzVhYjAiLCJhdXRoX3RpbWUiOjE1MDAwOTk4NjEsImlkcCI6ImxvY2FsIiwicm9sZSI6ImFkbWluaXN0cmF0b3IiLCJzY29wZSI6WyJvcGVuaWQiLCJwcm9maWxlIiwicm9sZXMiLCJXZWJBUEkiLCJvZmZsaW5lX2FjY2VzcyJdLCJhbXIiOlsicHdkIl19.CZAGtK5hvwgkMvX9NQ-8zTFr8Cv3SRVhM-u1WdqdLwI-qbdknfhhVFFHFpPzEWEJnKhsi3aE_BOb_UtRiDBWNHzlXAGmKSjtd70HOlT3dR9Sj_v09Ld15On3HihgfeDwOzIt10ZYwwjRr1tRCf6Ro41FQ2UrzBYcSFe47md7DSlxPXbjnQAHdu8gHMITFF8Nqx0V9OEw21fofRdBalOpvxf1IBhsJwWLyL4bLFYya8jNispK4MnN_tdaS8kxIMZ8iC_IUlhY4XEj5pkDBA9r8ad_Vn5WavO3Lmr4Tew4uBhlFhbE-Qr6EpErAEBVHVtJYs70XXGJJ7QQLoFNmO5M9w
content-type: text/plain
这篇关于IdentityServer4 + ASP.NET核心API + Angular:登录/身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!