I have a problem with authentication, I receive the token and I request a controller that has the attribute [Authorize], but I get a 401 error. How can I fix the error?
StartUp:
using System.Text;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using PWP.DataLayer.Context;
using PWP.Services.Repositories;
using PWP.Services.Services;
namespace PWP.Web
{
public class Startup
{
public IConfiguration Configuration { get; set; }
public Startup(IConfiguration configuration)
{
this.Configuration = configuration;
}
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(option =>
{
option.AddPolicy("EnableCors", builder =>
{
builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod().AllowCredentials().Build();
});
});
services.AddMvc();
services.AddDbContext<PWPDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("PWPDbContext"))
);
services.AddTransient<IUserRepository, UserRepository>();
services.AddTransient<IUserInfoRepository, UserInfoRepository>();
services.AddTransient<ISettingFRepository, SettingFRepository>();
services.AddTransient<IRecordRepository, RecordRepository>();
services.AddTransient<IMessageRepository, MessageRepository>();
services.AddTransient<IExpertiseRepository, ExpertiseRepository>();
services.AddTransient<IDocumentRepository, DocumentRepository>();
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(option =>
{
option.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = false,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "http://localhost:58810",
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("I#will#one#day#become#the#greatest#person#in#the#world,bigger#than#I#think")),
};
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvcWithDefaultRoute();
app.Run(async (context) =>
{
await context.Response.WriteAsync("Personal Web Site is Raning");
});
app.UseCors("EnableCors");
app.UseStaticFiles();
app.UseAuthentication();
}
}
}
AuthController:
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using PWP.Services.Repositories;
using PWP.ViewModels.LoginVM;
namespace PWP.Web.Controller
{
[Route("api/[controller]/[action]")]
[ApiController]
[Authorize]
public class AuthController : ControllerBase
{
private IUserRepository _userRepository;
public AuthController(IUserRepository userRepository)
{
_userRepository = userRepository;
}
[HttpPost]
[AllowAnonymous]
public async Task<IActionResult> PostLogin([FromForm] LoginVM login)
{
if (!ModelState.IsValid)
{
return BadRequest("??? ?????? ? ???? ???? ?????? ???");
}
if (!await _userRepository.IsExistsLogin(login))
{
return Unauthorized();
}
var SecretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("I#will#one#day#become#the#greatest#person#in#the#world,bigger#than#I#think"));
var signinCredentials = new SigningCredentials(SecretKey, SecurityAlgorithms.HmacSha256);
var tokenOption = new JwtSecurityToken(
issuer: "http://localhost:58810",
claims: new List<Claim>
{
new Claim (ClaimTypes.Role,"Admin"),
new Claim(ClaimTypes.Name,login.UserName),
},
expires: DateTime.Now.AddMinutes(30),
signingCredentials: signinCredentials
);
var tokenString = new JwtSecurityTokenHandler().WriteToken(tokenOption);
var user =await _userRepository.GetUserByName(login.UserName);
object sideMe = new
{
RoleName="Admin",
UserName=user.UserName,
Email=user.Email,
ImageAddress=user.imageAddress,
Token=tokenString
};
return Ok(sideMe);
}
}
}
MessageController:
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using PWP.Services.Repositories;
namespace PWP.Web.Controller
{
[Route("api/[controller]/[action]")]
[ApiController]
[Authorize]
public class MessagesController : ControllerBase
{
private IMessageRepository _messageRepository;
public MessagesController(IMessageRepository messageRepository)
{
_messageRepository = messageRepository;
}
[HttpGet]
public IActionResult GetMessages()
{
return new ObjectResult(_messageRepository.GetMessages());
}
[HttpPut("{id}")]
public async Task<IActionResult> PutMessage([FromForm] int messageId,[FromRoute] int id)
{
if (id != messageId)
{
return BadRequest();
}
var message = await _messageRepository.GetMessage(messageId);
message.ReadMessage = true;
await _messageRepository.PutMessage(message);
return Ok();
}
}
}
How can I solve this problem?
Please guide me if possible
Solve the problem by removing [Authorize] from the controller
But the need arose with authentication
question from:
https://stackoverflow.com/questions/65865737/receive-401-doses-of-host-authentication-using-tokens-in-asp-net-web-api-2-1 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…