gpt4 book ai didi

asp.net - 如何使用 JWT 对来自 Angular SPA 的 Web Api 2 进行用户身份验证?

转载 作者:行者123 更新时间:2023-12-04 20:06:32 26 4
gpt4 key购买 nike

我正在尝试设置从 AngularJS 单页应用程序 (SPA) 到基于 OWIN 构建的 Web Api 的身份验证。这是我所拥有的...

这是登录功能(API 中的 AuthenticationController 上的 POST 操作)

public HttpResponseMessage login(Credentials creds)
{
if (creds.Password == "password" && creds.Username.ToLower() == "username")
{
var user = new User { UserId = 101, Name = "John Doe", Role = "admin" };

var tokenDescriptor = new SecurityTokenDescriptor()
{
Subject = new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.Name, user.Name),
new Claim(ClaimTypes.Role, user.Role)
}),

AppliesToAddress = "http://localhost:/8080",
TokenIssuerName = "myApi",

SigningCredentials = new SigningCredentials(new InMemorySymmetricSecurityKey(TestApp.Api.Startup.GetBytes("ThisIsTopSecret")),
"http://www.w3.org/2001/04/xmldsig-more#hmac-sha256",
"http://www.w3.org/2001/04/xmlenc#sha256")
};

var tokenHandler = new JwtSecurityTokenHandler();
var token = tokenHandler.CreateToken(tokenDescriptor);
var tokenString = tokenHandler.WriteToken(token);

return Request.CreateResponse<LoginResponse>(HttpStatusCode.Accepted, new LoginResponse { User = user, AuthToken = tokenString });
}

return Request.CreateResponse(HttpStatusCode.Unauthorized);
}

这是我的 OWIN 启动配置
public void Configuration(IAppBuilder app)
{
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

HttpConfiguration config = new HttpConfiguration();
config.Routes.MapHttpRoute(
name: "Default",
routeTemplate: "{controller}"
);

var jsonSettings = config.Formatters.JsonFormatter.SerializerSettings;
jsonSettings.Formatting = Formatting.Indented;
jsonSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

app.UseWebApi(config);

app.UseJwtBearerAuthentication(
new JwtBearerAuthenticationOptions
{
AuthenticationMode = AuthenticationMode.Active,
AllowedAudiences = new[] { "http://localhost:8080" },
IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
{
new SymmetricKeyIssuerSecurityTokenProvider("myApp", TestApp.Api.Startup.GetBytes("ThisIsTopSecret"))
}
});
}

这是我用来调用 API 中具有 Authorized 属性的 Controller 的 Angular 代码。
$http({ method: 'GET', url: 'http://localhost:5000/Admin', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + Session.token }})
.then(function (res) {
return res.data;
});

当我登录时,我将返回的 token 作为字符串。然后我将它存储在我的客户端 session 中。然后我把它放在我的标题中以备后续请求。

当我尝试在 API 中调用“授权”操作时,即使我的 token 是通过请求的 header 传入的,我也会收到 401 响应。

我是 JWT 的新手,所以我可能完全偏离了我的方法。任何建议都会很棒。

最佳答案

我相信这是一个操作顺序。将 app.UseJwt 语句移到 app.UseWebApi 行上方。

    app.UseJwtBearerAuthentication(
new JwtBearerAuthenticationOptions
{
AuthenticationMode = AuthenticationMode.Active,
AllowedAudiences = new[] { "http://localhost:8080" },
IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
{
new SymmetricKeyIssuerSecurityTokenProvider("myApp", TestApp.Api.Startup.GetBytes("ThisIsTopSecret"))
}
});

app.UseWebApi(config);

关于asp.net - 如何使用 JWT 对来自 Angular SPA 的 Web Api 2 进行用户身份验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24813047/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com