代码之家  ›  专栏  ›  技术社区  ›  JED

无法获取当前用户或授权

  •  1
  • JED  · 技术社区  · 6 年前

    正在开发Angular2/ASP.NET Core2.1应用程序。登录时,我可以从前端console.log jwt令牌,但当我尝试使用 [Authorize] 属性,我得到401错误。如果删除该属性,并尝试使用 var currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); 我会立即被发送回前端,并通过解析器接收错误消息。

    当前用户数据似乎没有随请求一起发送到后端。或者它没有被储存?或者我没有正确访问它?

    帐户列表.resolver.ts

    import { Resolve, Router, ActivatedRouteSnapshot } from '@angular/router';
    import { Account } from '../../_models/account';
    import { Injectable } from '@angular/core';
    import { AccountService } from '../../_services/account.service';
    import { AlertifyService } from '../../_services/alertify.service';
    import { Observable } from 'rxjs/Observable';
    import 'rxjs/add/observable/of';
    import 'rxjs/add/operator/catch';
    
    @Injectable()
    export class AccountListResolver implements Resolve<Account[]> {
      pageSize = 5;
      pageNumber = 1;
    
      constructor(private accountService: AccountService,
        private router: Router,
        private alertify: AlertifyService) {
      }
    
      resolve(route: ActivatedRouteSnapshot): Observable<Account[]> {
        return this.accountService.getAccounts(this.pageNumber, this.pageSize).catch(error => {
          this.alertify.error('Problem retrieving data');
          this.router.navigate(['/dashboard']);
          return Observable.of(null);
        });
      }
    }
    


    帐户服务.ts

    import { Injectable } from '@angular/core';
    import { environment } from '../../environments/environment';
    import { Account } from '../_models/account';
    import 'rxjs/add/operator/map';
    import 'rxjs/add/operator/catch';
    import 'rxjs/add/observable/throw';
    import { PaginatedResult } from '../_models/pagination';
    import { HttpClient, HttpParams } from '@angular/common/http';
    
    @Injectable()
    export class AccountService {
      baseUrl = environment.apiUrl;
    
      constructor(private authHttp: HttpClient) { }
    
      getAccounts(page?, itemsPerPage?, accountParams?: any) {
        const paginatedResult: PaginatedResult<Account[]> = new PaginatedResult<Account[]>();
        let params = new HttpParams();
    
        if (page != null && itemsPerPage != null) {
          params = params.append('pageNumber', page);
          params = params.append('pageSize', itemsPerPage);
        }
    
        // if (accountParams != null) {
        //   params = params.append('paramName', accountParams.paramName);
        // }
    
        return this.authHttp
          .get<Account[]>(this.baseUrl + 'accounts', { observe: 'response', params })
          .map(response => {
            paginatedResult.result = response.body;
            if (response.headers.get('Pagination') != null) {
              paginatedResult.pagination = JSON.parse(response.headers.get('Pagination'));
            }
    
            return paginatedResult;
          });
      }
    }
    


    会计控制员

    [Authorize]
    [Route("api/[controller]")]
    public class AccountsController : Controller
    {
        private readonly IBaseRepository _repo;
        private readonly IMapper _mapper;
    
        public AccountsController(IBaseRepository repo, IMapper mapper)
        {
            _mapper = mapper;
            _repo = repo;
        }
    
        [HttpGet]
        public async Task<IActionResult> GetAccounts([FromQuery] AccountParams accountParams)
        {
            var currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);
            //^^^WHERE IT BREAKS WHEN AUTHORIZATION ATTRIBUTE IS REMOVED
    
            //code to generate list of accounts to return
            accountParams.UserId = currentUserId;
    
            var accounts = await _repo.GetAccounts(accountParams);
    
            var accountsToReturn = _mapper.Map<IEnumerable<AccountForListDto>>(accounts);
    
            Response.AddPagination(accounts.CurrentPage, accounts.PageSize, accounts.TotalCount, accounts.TotalPages);
    
            return Ok(accountsToReturn);
        }
    }
    


    **编辑**

    启动.cs

    public void ConfigureServices(IServiceCollection services)
    {
        var key = Encoding.ASCII.GetBytes(Configuration.GetSection("AppSettings:Token").Value);
    
        services.AddDbContext<DataContext>(x => x
            .UseSqlServer(Configuration.GetConnectionString("DefaultConnection"), b =>
                b.MigrationsAssembly(("MyApp.App")))
            .ConfigureWarnings(warnings => warnings.Ignore(CoreEventId.IncludeIgnoredWarning)));
    
        services.AddMvc()
            .AddJsonOptions(opt =>
            {
                opt.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
            })
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    
        services.AddSpaStaticFiles(configuration => { configuration.RootPath = "ClientApp/dist"; });
    
        services.AddTransient<Seed>();
    
        services.AddCors();
    
        services.AddAutoMapper();
    
        services.AddScoped<IAuthRepository, AuthRepository>();
    
        services.AddScoped<IBaseRepository, BaseRepository>();
    
        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(key),
                    ValidateIssuer = false,
                    ValidateAudience = false
                };
            });
    
        services.AddScoped<LogUserActivity>();
    }
    
    public void ConfigureDevelopmentServices(IServiceCollection services)
    {
        var key = Encoding.ASCII.GetBytes(Configuration.GetSection("AppSettings:Token").Value);
    
        services.AddDbContext<DataContext>(x => x
            .UseSqlServer(Configuration.GetConnectionString("DefaultConnection"), b =>
                b.MigrationsAssembly(("MyApp.App")))
            .ConfigureWarnings(warnings => warnings.Ignore(CoreEventId.IncludeIgnoredWarning)));
    
        services.AddMvc()
            .AddJsonOptions(opt =>
            {
                opt.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
            })
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    
        services.AddSpaStaticFiles(configuration => { configuration.RootPath = "ClientApp/dist"; });
    
        services.AddTransient<Seed>();
    
        services.AddCors();
    
        services.AddAutoMapper();
    
        services.AddScoped<IAuthRepository, AuthRepository>();
    
        services.AddScoped<IBaseRepository, BaseRepository>();
    
        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(key),
                    ValidateIssuer = false,
                    ValidateAudience = false
                };
            });
    
        services.AddScoped<LogUserActivity>();
    }
    
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler(builder =>
            {
                builder.Run(async context =>
                {
                    context.Response.StatusCode = (int) HttpStatusCode.InternalServerError;
    
                    var error = context.Features.Get<IExceptionHandlerFeature>();
                    if (error != null)
                    {
                        context.Response.AddApplicationError(error.Error.Message);
                        await context.Response.WriteAsync(error.Error.Message);
                    }
                });
            });
        }
    
        app.ConfigureSwagger(Assembly.GetExecutingAssembly());
    
        app.UseCors(x => x.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin().AllowCredentials());
        app.UseDefaultFiles();
        app.UseHttpsRedirection();
        app.UseStaticFiles();
    
        app.UseSpaStaticFiles();
    
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller}/{action=Index}/{id?}");
        });
    
        app.UseSpa(spa =>
        {
            // To learn more about options for serving an Angular SPA from ASP.NET Core,
            // see https://go.microsoft.com/fwlink/?linkid=864501
    
            spa.Options.SourcePath = "ClientApp";
    
            if (env.IsDevelopment())
            {
                spa.UseProxyToSpaDevelopmentServer("http://localhost:4200");
                //spa.UseAngularCliServer(npmScript: "start");
            }
        });
    }
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   blowdart    6 年前

    您添加了jwt授权处理程序吗?

    在你的初创公司.cs

    1. app.UseAuthentication() Configure 方法?
    2. 是以前吗 app.UseMvc() 是吗?
    3. app.AddAuthentication() 在你的 ConfigureServices 方法?
    4. 是以前吗 app.AddMvc() 是吗?
    5. 有电话给 AddJwtBearer() 在你的 配置服务 方法悬挂 停止呼叫 AddAuthentication() 是吗?
    6. 您在jwtbearer服务的选项中有正确的密钥吗?
    7. 如果jwtbearer不是您唯一的身份验证机制(例如,您还添加了标识),那么您是在 Authorize 属性?

    从您的配置来看,configure方法中缺少app.useAuthentication()。

    所以你需要把它放在app.usemvc()之前,就像这样;

    app.UseSpaStaticFiles();
    app.UseAuthentication()
    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller}/{action=Index}/{id?}");
    });