1、Bearer授权操作,添加如下代码
services.AddSwaggerGen(options => { options.AddSecurityDefinition("Bearer", new ApiKeyScheme { Description = "JWT Bearer 授权 "Authorization: Bearer+空格+token"", Name = "Authorization", In = "header", Type = "apiKey" }); });
可以看到swagger的授权按钮:
点击授权按钮:
填写授权的access_token授权
2、OAuth2授权,配置好相关的客户端
添加授权类:
/// <summary> /// IdentityServer4认证处理 /// </summary> public class IdentityServer4OAuth2OperationFilter : IOperationFilter { public void Apply(Operation operation, OperationFilterContext context) { if (operation.Security == null) operation.Security = new List<IDictionary<string, IEnumerable<string>>>(); var oAuthRequirements = new Dictionary<string, IEnumerable<string>> { {"oauth2", new List<string> { "openid", "profile", "UserServicesApi" }} }; operation.Security.Add(oAuthRequirements); } }
options.AddSecurityDefinition("oauth2", new OAuth2Scheme { Type = "oauth2", Flow = "implicit", AuthorizationUrl = "http://localhost:30000/connect/authorize", Scopes = new Dictionary<string, string> { { "UserServicesApi", "用户服务" } } }); options.OperationFilter<IdentityServer4OAuth2OperationFilter>();
授权如下,点击授权会转到授权页面
来看下地址:
http://localhost:30000/Account/Login
?ReturnUrl=%2Fconnect%2Fauthorize%2Fcallback%3F
response_type%3Dtoken%26
client_id%3Dxujiemingapi%26
redirect_uri%3Dhttp%253A%252F%252Flocalhost%253A20001%252Fswagger%252Foauth2-redirect.html%26scope%3DUserServicesApi%26state%3DRnJpIE1heSAxMSAyMDE4IDE4OjE0OjE4IEdNVCswODAwICjkuK3lm73moIflh4bml7bpl7Qp
登录授权后成功