コード例 #1
0
        public static void AddJwtCookieAuthentication(this IServiceCollection services,
                                                      string secret_key, string issuer = "NC", string audience = "NCUser")
        {
            var tokenValidationParameters = new TokenValidationParameters
            {
                // The signing key must match!
                ValidateIssuerSigningKey = true,
                IssuerSigningKey         = SigningKey.GetSigningKey(secret_key),

                // Validate the JWT Issuer (iss) claim
                ValidateIssuer = true,
                ValidIssuer    = issuer,

                // Validate the JWT Audience (aud) claim
                ValidateAudience = true,
                ValidAudience    = audience,

                // Validate the token expiry
                ValidateLifetime = true,

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

            services.AddAuthentication(o =>
            {
                o.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                o.DefaultChallengeScheme    = CookieAuthenticationDefaults.AuthenticationScheme;
                o.DefaultSignInScheme       = CookieAuthenticationDefaults.AuthenticationScheme;
            }
                                       ).AddCookie((options) => {
                options.Cookie.Name      = "access_token";
                options.Cookie.HttpOnly  = true;
                options.TicketDataFormat = new CustomJwtDataFormat(
                    SecurityAlgorithms.HmacSha256,
                    tokenValidationParameters);
                options.Events.OnRedirectToAccessDenied = (context) =>
                {
                    return(Task.Run(() =>
                    {
                        context.Response.StatusCode = 401;
                    }));
                };
                options.Events.OnRedirectToLogin = (context) => {
                    return(Task.Run(() => {
                        context.Response.StatusCode = 401;
                    }));
                };
            });
        }
コード例 #2
0
        private void addTokenInCookie(HttpClient httpClient, string username, string[] roles,
                                      string cookieDomain,
                                      IList <KeyValuePair <string, string> > claims,
                                      string secretKey,
                                      string audience, string issuer)
        {
            httpClient.DefaultRequestHeaders.Remove("Cookie");
            var signingKey = SigningKey.GetSigningKey(secretKey);
            var options    = new TokenProviderOptions
            {
                Audience           = audience,
                Issuer             = issuer,
                SigningCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256),
            };
            var jwtService = new JwtService();

            JsonWebToken token;

            if (claims != null)
            {
                claims.Add(new KeyValuePair <string, string>("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", username));
                token = jwtService.GenerateJsonWebToken(username, roles, options, claims.ToArray());
            }
            else
            {
                token = jwtService.GenerateJsonWebToken(username, roles, options, new KeyValuePair <string, string>("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", username));
            }


            var cookieOptions = new CookieOptions
            {
                Domain  = cookieDomain,
                Expires = DateTimeOffset.UtcNow.AddHours(8).AddDays(1).AddMinutes(-5)
            };

            var cookies = new List <string> {
                $"access_token={token.AccessToken}",
                $"username={username}",
                $"expires_in={token.ExpiresIn}"
            };

            httpClient.DefaultRequestHeaders.Add("Cookie", string.Join(";", cookies));
        }