我想删除授权,即仅为我的web api应用程序移除授权令牌身份验证。并且授权应该照常用于其他控制台应用程序,如postman.If如何才能实现单独的swagger 。提供我使用swashbuckle nuget包进行申请。
答案 0 :(得分:0)
以下是我尝试过的代码,我使用swagger和其他网址的自定义授权,它在本地环境中工作正常,但我的api无法通过https服务器中的其他api部署后访问,未经授权错误。
public class CustomAuthorization : AuthorizationFilterAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
Uri currentUrl = HttpContext.Current.Request.UrlReferrer;
if(currentUrl != null)
{
if (currentUrl.Segments.Contains("swagger"))
{
string accessToken = "";
using (var client = new HttpClient())
{
var form = new Dictionary<string, string>
{
{"grant_type", "password"},
{"username", "user"},
{"password", "password"},
{"scope","scope"}
};
string url = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority);
var tokenResponse = client.PostAsync(url + "/token", new FormUrlEncodedContent(form)).Result;
var token = tokenResponse.Content.ReadAsAsync<AuthorizationToken>(new[] { new JsonMediaTypeFormatter() }).Result;
accessToken = token.access_token;
HttpContext.Current.Request.Headers.Add("Authorization", "Bearer " + accessToken);
}
}
}
else
{
var principal = actionContext.RequestContext.Principal as ClaimsPrincipal;
if (!principal.Identity.IsAuthenticated)
{
AuthorizationMessage autho = new AuthorizationMessage();
autho.Message = "Missing access credentials.";
autho.Type = "Unauthorize";
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized, autho);
}
}
}
class AuthorizationMessage
{
public string Type { get; set; }
public string Message { get; set; }
}
}