Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
141 views
in Technique[技术] by (71.8m points)

asp.net core - Receive 401 doses of host authentication using tokens in asp net web api 2.1

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();
        }
    }
}

enter image description here

enter image description here

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Just add app.UseAuthentication();

Like this:

 app.UseAuthentication();
 app.UseAuthorization();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...