1

从这个很棒的教程中,我已经能够在服务器上生成一个令牌并将其保存在本地存储中。 https://stormpath.com/blog/token-authentication-asp-net-core

但是当将令牌发送到具有 [Authorize] 属性的控制器方法时,我得到 401

我的 startup.cs 看起来像这样

    //ConfigureTokenSecurity(app, env);
    var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretKey));

    var options = new TokenProviderOptions
    {
        //Audience = "ExampleAudience",
        //Issuer = "ExampleIssuer",
        SigningCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256),
    };

    app.UseMiddleware<TokenProviderMiddleware>(Options.Create(options));

    var tokenValidationParameters = new TokenValidationParameters
    {
        // The signing key must match!
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = signingKey,

        // Validate the JWT Issuer (iss) claim
        ValidateIssuer = false,
        //ValidIssuer = "ExampleIssuer",

        // Validate the JWT Audience (aud) claim
        ValidateAudience = false,
        //ValidAudience = "ExampleAudience",

        // Validate the token expiry
        ValidateLifetime = false,

        // If you want to allow a certain amount of clock drift, set that here:
        ClockSkew = TimeSpan.Zero
    };

    app.UseJwtBearerAuthentication(new JwtBearerOptions
    {
        AutomaticAuthenticate = true,
        AutomaticChallenge = true,
        TokenValidationParameters = tokenValidationParameters
    });

打字稿请求看起来像这样

 public getValuesHandler(
        onSuccess: (values: string[]) => void,
        onError: (error: any) => void = undefined
    ): void {
        debugger;
        let headers = new Headers({ 'Authorization': 'Bearer ' + this.authorisationService.token, 'Expires': this.authorisationService.tokenExpires, 'Content-Type': 'application/json'  });
        let options = new RequestOptions({ headers: headers });

        const url = "/api/sandbox/get";
        this.http.get(url, options)
            .map(response => <string[]>response.json())
            .subscribe(onSuccess, error => {
                this.recordError(url, error);
                if (onError) onError(error);
            });
    }

奇怪的是,如果我运行令牌

TokenHandler.ValidateToken(t, tokenValidationParameters, out validatedToken);

没有承载它返回一个有效的令牌,但是如果令牌在开始时有一个“承载”,我会得到一个“JWT 格式不正确的异常”

4

0 回答 0