【发布时间】:2020-10-04 03:35:18
【问题描述】:
我试过var claimsIdentity = new ClaimsIdentity(GetUserClaims(user), token);,但我不知道如何使用它
我的启动.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddDistributedMemoryCache();
services.AddSession(options => {
options.IdleTimeout = TimeSpan.FromMinutes(1);
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
//Provide a secret key to Encrypt and Decrypt the Token
var SecretKey = Encoding.ASCII.GetBytes
("YourKey-2374-OFFKDI940NG7:56753253-tyuw-5769-0921-kfirox29zoxv");
//Configure JWT Token Authentication
services.AddAuthentication(auth =>
{
auth.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
auth.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(token =>
{
token.RequireHttpsMetadata = false;
token.SaveToken = true;
token.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
//Same Secret key will be used while creating the token
IssuerSigningKey = new SymmetricSecurityKey(SecretKey),
ValidateIssuer = true,
//Usually, this is your application base URL
ValidIssuer = "http://localhost:45092/",
ValidateAudience = true,
//Here, we are creating and using JWT within the same application.
//In this case, base URL is fine.
//If the JWT is created using a web service, then this would be the consumer URL.
ValidAudience = "http://localhost:45092/",
RequireExpirationTime = true,
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero
};
});
services.AddControllersWithViews();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseSession();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
我的服务.cs
public string LoginUser(string UserID, string Password)
{
var user = UserList.SingleOrDefault(x => x.UserId == UserID);
if (user == null)
return null;
if (Password == user.Password)
{
//Authentication successful, Issue Token with user credentials
//Provide the security key which is given in
//Startup.cs ConfigureServices() method
var key = Encoding.ASCII.GetBytes
("YourKey-2374-OFFKDI940NG7:56753253-tyuw-5769-0921-kfirox29zoxv");
//Generate Token for user
var JWToken = new JwtSecurityToken(
issuer: "http://localhost:45092/",
audience: "http://localhost:45092/",
claims: GetUserClaims(user),
notBefore: new DateTimeOffset(DateTime.Now).DateTime,
expires: new DateTimeOffset(DateTime.Now.AddDays(1)).DateTime,
//Using HS256 Algorithm to encrypt Token
signingCredentials: new SigningCredentials
(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
);
string token = new JwtSecurityTokenHandler().WriteToken(JWToken);
//var claimsIdentity = new ClaimsIdentity(GetUserClaims(user), token);
//return claimsIdentity;
return token;
}
else
{
return null;
}
}
private List<User> UserList = new List<User>
{
new User {
UserId = "jsmith@email.com",
Password = "test", Email = "jsmith@email.com",
FirstName = "John", LastName = "Smith",
Phone = "356-735-2748", AccesLevel = "Director",
ReadOnly = "true"
}
};
private IEnumerable<Claim> GetUserClaims(User user)
{
IEnumerable<Claim> claims = new Claim[]
{
new Claim(ClaimTypes.Name, user.FirstName + " " + user.LastName),
new Claim("USERID", user.UserId),
new Claim("EMAILID", user.Email),
new Claim("PHONE", user.Phone),
new Claim("ACCESS_LEVEL", user.AccesLevel.ToUpper()),
new Claim("READ_ONLY", user.ReadOnly.ToUpper())
};
return claims;
}
我的控制器.cs
public IActionResult LoginUser(User user)
{
TokenProvider _tokenProvider = new TokenProvider();
var userToken = _tokenProvider.LoginUser(user.UserId.Trim(), user.Password);
if (userToken != null)
{
//Save token in session object
HttpContext.Session.SetString("JWToken", userToken);
bool islogin = User.Identity.IsAuthenticated;
}
return Redirect("~/Home/Index");
}
最后,我的 Index.cshtml
@model Colegio.Models.User
@{
ViewData["Title"] = "Home Page";
}
@if (User.Identity.IsAuthenticated)
{
<div class="row">
You are Logged in as
<span style="font-size:large;color:forestgreen;">
@User.Identity.Name
</span>
</div>
<div class="row" style="padding-top:50px;">
@Html.ActionLink("Log Off", "Logoff",
"Home", null, new { @class = "btn btn-primary btn-lg rph-login-button" })
</div>
}
当我在 service.ch 中使用 var claimsIdentity = new ClaimsIdentity(GetUserClaims(user), token); 时,属性 IsAuthenticated 为 true,但我必须做什么?
【问题讨论】:
标签: c# asp.net-core razor jwt razor-pages