如何在OAuth回调中生成JwtToken

时间:2019-06-25 00:24:59

标签: .net-core oauth-2.0 jwt

访问用户信息端点后,需要在OAuth回调中生成我自己的JwtToken

我有一个在AngularJS中运行的应用程序,并且在.NetCore中有一些API。我需要使用OAuth服务器进行身份验证。 OAuth服务器首先返回访问令牌。使用访问令牌,我访问用户信息端点以获取用户信息。之后,我需要生成我的JwtToken并将其返回到UI,以便可以将其存储在本地存储中,并随每次API调用一起发送。

我知道如何生成JwtToken,但是我不知道如何在回调方法的末尾将其发送回UI。我什至不知道这是否是正确的方法。我无法在用户界面中完成所有操作,因为我的OAuth服务器需要客户端和机密,而我不能在用户端使用它。

       services.AddAuthentication()
        .AddJwtBearer("JwtToken", options =>
        {
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = false,
                ValidateAudience = false,
                ValidateLifetime = true,
                ValidateIssuerSigningKey = true,
                //ValidIssuer = Configuration["Jwt:Issuer"],
                // ValidAudience = Configuration["Jwt:Issuer"],
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("my key"))
           };
           options.ForwardDefault = oauth.Name;
        })
        .AddOAuth(oauth.Name, AuthConfiguration(oauth))


    private System.Action<OAuthOptions> AuthConfiguration(AuthConfiguration auth)
    {
        return options =>
        {
            // Configure the Auth0 Client ID and Client Secret
            options.ClientId = auth.ClientID;
            options.ClientSecret = auth.Secret;

            options.CallbackPath = new PathString(auth.Callback);

            // Configure the Auth0 endpoints
            options.AuthorizationEndpoint = auth.AuthorizationEndpoint;
            options.TokenEndpoint = auth.TokenEndpoint;
            options.UserInformationEndpoint = auth.UserInformationEndpoint;

            // To save the tokens to the Authentication Properties we need to set this to true
            // See code in OnTicketReceived event below to extract the tokens and save them as Claims
            //options.SaveTokens = true;

            // Set scope to openid. See https://auth0.com/docs/scopes
            options.Scope.Clear();
            options.Scope.Add("openid");
            options.Scope.Add("profile");

            options.Events = new OAuthEvents
            {
                // When creating a ticket we need to manually make the call to the User Info endpoint to retrieve the user's information,
                // and subsequently extract the user's ID and email adddress and store them as claims
                OnCreatingTicket = async context =>
                {
                        //// Retrieve user info
                        var request = new HttpRequestMessage(HttpMethod.Get, context.Options.UserInformationEndpoint);
                        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", context.AccessToken);
                        request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                        var response = await context.Backchannel.SendAsync(request, context.HttpContext.RequestAborted);
                        response.EnsureSuccessStatusCode();

                        // Extract the user info object
                        var user = JObject.Parse(await response.Content.ReadAsStringAsync());

                        // Add the Name Identifier claim
                        var userId = user.Value<string>("sub");
                        if (!string.IsNullOrEmpty(userId))
                        {
                            context.Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, userId, ClaimValueTypes.String, context.Options.ClaimsIssuer));
                        }

                        // Add the Name claim
                        email = user.Value<string>("email");

                }
            };
        };
    }

1 个答案:

答案 0 :(得分:0)

创建一个控制器,并将对该代码的调用作为该控制器上的GET方法添加。它将返回您的方法生成的字符串