ASP.NET Core 5 MVC web应用程序-通过xamarin登录



我开发了我的ASP.NET Core 5 MVC应用程序;个人登录";。在应用程序中注册和登录很好。

现在我想使用Xamarin应用程序的API登录到我的MVC web应用程序。从我读到的";JWT";应该使用。我想用尽可能多的";标准";尽可能在后端,最好使用标准API。

不幸的是,我尝试过的所有网站都无法帮助我(解决方案已损坏,不存在URL,…(。

有人能给我发一个工作教程或后台示例吗。

谢谢,杰彭

通过api,您可以将jwt身份验证配置为这样。

  1. Startup

    public void ConfigureServices(IServiceCollection services)
    {
    services.AddAuthentication(x =>
    {
    x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    })
    .AddJwtBearer(o =>
    {
    o.TokenValidationParameters = new TokenValidationParameters
    {
    NameClaimType = JwtClaimTypes.Name,
    RoleClaimType = JwtClaimTypes.Role,
    //The previous three items are required
    ValidIssuer = "http://localhost:5000",
    ValidAudience = "api",
    IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("this is a long key"))
    /***********************************default TokenValidationParameters parameter***********************************/
    // RequireSignedTokens = true,
    // SaveSigninToken = false,
    // ValidateActor = false,
    };
    });
    services.AddControllers();
    }
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
    //...
    app.UseRouting();
    app.UseAuthentication();
    app.UseAuthorization();
    //...
    }
    
  2. 申请一个令牌,在操作中生成一个字符串令牌。

    public IActionResult Authenticate()
    {
    var tokenHandler = new JwtSecurityTokenHandler();
    var key = Encoding.ASCII.GetBytes("this is a long key");
    var authTime = DateTime.UtcNow;
    var expiresAt = authTime.AddDays(7);
    var tokenDescriptor = new SecurityTokenDescriptor
    {
    Subject = new ClaimsIdentity(new Claim[]
    {
    new Claim(JwtClaimTypes.Audience,"api"),
    new Claim(JwtClaimTypes.Issuer,"http://localhost:5000"),
    new Claim(JwtClaimTypes.Id, "10"),
    new Claim(JwtClaimTypes.Name, "my name"),
    new Claim(JwtClaimTypes.Email, "email"),
    }),
    Expires = expiresAt,
    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
    };
    var token = tokenHandler.CreateToken(tokenDescriptor);
    var tokenString = tokenHandler.WriteToken(token);
    return Ok(tokenString);
    }
    
  3. Xamarin App接收令牌并保存。当Xamarin应用程序访问授权资源时,它可以使用此header携带此令牌。

    var client = new HttpClient();
    var token = client.GetAsync("[url that get the token] ");
    client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");
    client.GetAsync("[url that get the authorized resource] ");
    

最新更新