示例#1
0
        public string createAccessToken()
        {
            string secret   = TokenSecret;
            string issuer   = "http://localhost.local/";
            string audience = "http://localhost.local/";

            var claims = new[]
            {
                new Claim("name", this.email),
                new Claim("role", this.role)
            };

            var signingKey = new Microsoft.IdentityModel.
                             Tokens.SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret));

            var creds = new Microsoft.IdentityModel.
                        Tokens.SigningCredentials(signingKey,
                                                  Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256);

            var token = new System.IdentityModel.Tokens.Jwt.JwtSecurityToken(
                issuer: issuer,
                audience: audience,
                expires: DateTime.Now.AddMinutes(30),
                claims: claims,
                signingCredentials: creds
                );

            return(new System.IdentityModel.Tokens.
                   Jwt.JwtSecurityTokenHandler().WriteToken(token));
        }
示例#2
0
        //[HttpGet]
        //[HttpPost]
        public IActionResult Token(LoginViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(ValidationProblem(ModelState));
            }
            if (!(model.User == "jim" && model.Password == "123456"))
            {
                return(BadRequest());
            }
            var claims = new System.Security.Claims.Claim[]
            {
                new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.Name, "jim"),
                // Role 授权
                new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.Role, "user"),
                // Claim 授权
                //new System.Security.Claims.Claim("SuperAdminOnly", "true"),
            };
            var key   = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(_jwtSettings.SecretKey));
            var creds = new Microsoft.IdentityModel.Tokens.SigningCredentials(key, Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256);

            var token = new System.IdentityModel.Tokens.Jwt.JwtSecurityToken(_jwtSettings.Issuser,
                                                                             _jwtSettings.Audience,
                                                                             claims,
                                                                             DateTime.Now,
                                                                             DateTime.Now.AddMinutes(30),
                                                                             creds);

            return(Ok(new { token = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler().WriteToken(token) }));
        }
示例#3
0
        public async Task <IActionResult> LogIn(string submitbutton, string username, string password)
        {
            HttpClient client = _httpContextFactory.CreateClient("TGSClient");

            AppUser userModel = new AppUser();

            userModel.UserName = username;
            userModel.Password = password;

            HttpResponseMessage response = await client.PostAsJsonAsync <AppUser>("api/Authorization/LogIn", userModel);

            if (response.IsSuccessStatusCode)
            {
                JWTToken jwt = await response.Content.ReadFromJsonAsync <JWTToken>();

                System.IdentityModel.Tokens.Jwt.JwtSecurityToken jwtSecurityToken = new System.IdentityModel.Tokens.Jwt.JwtSecurityToken(jwt.Token);
                HttpContext.User = new ClaimsPrincipal(new ClaimsIdentity(jwtSecurityToken.Claims));

                _httpContextCookieController.Set("token", jwt.Token, jwt.Expire);

                return(Redirect("~/"));
            }
            else
            {
                return(View());
            }
        }
 internal static bool ValidateToken(string token, out System.IdentityModel.Tokens.Jwt.JwtSecurityToken JwtToken)
 {
     JwtToken = null;
     try
     {
         var tokenHandler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler();
         JwtToken = tokenHandler.ReadToken(token) as System.IdentityModel.Tokens.Jwt.JwtSecurityToken;
         if (JwtToken == null)
         {
             return(false);
         }
         var validationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters()
         {
             RequireExpirationTime = true,
             ValidateIssuer        = false,
             ValidateAudience      = false,
             IssuerSigningKey      = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(symmetricKey)
         };
         Microsoft.IdentityModel.Tokens.SecurityToken securityToken;
         tokenHandler.ValidateToken(token, validationParameters, out securityToken);
         return(true);
     }
     catch (Microsoft.IdentityModel.Tokens.SecurityTokenValidationException e)
     {
         Console.WriteLine($"Token Expired!: {e}");
         return(false);
     }
 }
示例#5
0
        public ActionResult Callback()
        {
            //取得返回的code
            var code = Request.QueryString["code"];

            if (code == null)
            {
                ViewBag.access_token = "沒有正確的code...";
                return(View("index"));
            }

            //從Code取回toke
            var token = Utility.GetTokenFromCode(code,
                                                 "___這邊要換成你的client_id___",                     //TODO:請更正為你自己的 client_id
                                                 "___請更正為你自己的 client_secret___",               //TODO:請更正為你自己的 client_secret
                                                 "http://localhost:52643/LineLogin/Callback"); //TODO:請檢查此網址必須與你的LINE Login後台Call back URL相同

            //利用access_token取得用戶資料
            var user = Utility.GetUserProfile(token.access_token);
            //利用id_token取得Claim資料
            var JwtSecurityToken = new System.IdentityModel.Tokens.Jwt.JwtSecurityToken(token.id_token);
            var email            = "";

            //如果有email
            if (JwtSecurityToken.Claims.ToList().Find(c => c.Type == "email") != null)
            {
                email = JwtSecurityToken.Claims.First(c => c.Type == "email").Value;
            }

            //ViewBag
            ViewBag.email        = email;
            ViewBag.access_token = token.access_token;
            ViewBag.displayName  = user.displayName;
            return(View("index"));
        }
示例#6
0
        public string Protect(AuthenticationTicket data)
        {
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }

            string audienceId           = Utils.Configuration.TokenAudienceId;
            string symmetricKeyAsBase64 = Utils.Configuration.TokenAudienceSecret;
            var    keyByteArray         = TextEncodings.Base64Url.Decode(symmetricKeyAsBase64);
            //var signingKey = new System.IdentityModel.Tokens.SigningCredentials(new System.IdentityModel.Tokens.InMemorySymmetricSecurityKey(keyByteArray),
            //												SignatureAlgorithm,
            //												DigestAlgorithm);
            var signingKey = new Microsoft.IdentityModel.Tokens.SigningCredentials(new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(keyByteArray),
                                                                                   SignatureAlgorithm,
                                                                                   DigestAlgorithm);

            var issued  = data.Properties.IssuedUtc;
            var expires = data.Properties.ExpiresUtc;
            var token   = new System.IdentityModel.Tokens.Jwt.JwtSecurityToken(_issuer, audienceId, data.Identity.Claims,
                                                                               issued.Value.UtcDateTime, expires.Value.UtcDateTime, signingKey);
            var handler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler();
            var jwt     = handler.WriteToken(token);

            return(jwt);
        }
示例#7
0
        private string IssueJwtToken(System.IdentityModel.Tokens.Jwt.JwtSecurityToken aadToken)
        {
            var msKey = GetTokenSignKey();

            var msSigningCredentials = new Microsoft.IdentityModel.Tokens
                                       .SigningCredentials(msKey, Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256Signature);

            var claimsIdentity = new System.Security.Claims.ClaimsIdentity(new List <Claim>()
            {
                new Claim(ClaimTypes.NameIdentifier, "*****@*****.**"),
                new Claim(ClaimTypes.Role, "admin"),
            }, "MassRover.Authentication");

            var msSecurityTokenDescriptor = new Microsoft.IdentityModel.Tokens.SecurityTokenDescriptor()
            {
                Audience           = "massrover.client",
                Issuer             = "massrover.authservice",
                Subject            = claimsIdentity,
                Expires            = DateTime.UtcNow.AddHours(8),
                SigningCredentials = msSigningCredentials
            };

            var tokenHandler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler();

            var plainToken = tokenHandler.CreateToken(msSecurityTokenDescriptor);

            var signedAndEncodedToken = tokenHandler.WriteToken(plainToken);

            return(signedAndEncodedToken);
        }
示例#8
0
        public ActionResult ImplicitLanding(string idToken)
        {
            logger.Debug("Post ImplicitLanding");
            // GetInfoResponse getInfoResponse = new GetInfoResponse();
            System.Security.Claims.ClaimsPrincipal           jsonPayload   = null;
            System.IdentityModel.Tokens.Jwt.JwtSecurityToken tokenReceived = null;

            //string clientId = appSettings["oidc.spintweb.clientId"];
            string issuer   = appSettings["oidc.issuer"];
            string audience = appSettings["oidc.spintweb.clientId"];

            jsonPayload = oktaOidcHelper.ValidateIdToken(idToken, issuer, audience);
            if (jsonPayload.Identity.IsAuthenticated)
            {
                TempData["errMessage"] = "Id Token Validated";
                tokenReceived          = new System.IdentityModel.Tokens.Jwt.JwtSecurityToken(idToken);
            }
            else
            {
                TempData["errMessage"] = "Invalid ID Token!";
            }
            TempData["idToken"] = idToken;
            TempData["oktaOrg"] = MvcApplication.apiUrl;

            return(View("ImplicitLanding", tokenReceived));
        }
示例#9
0
        /// <summary>
        /// Instantiates a new token
        /// </summary>
        /// <param name="accesstoken">Accesstoken of which to instantiate a new token</param>
        public GenericToken(string accesstoken)
        {
            if (string.IsNullOrWhiteSpace(accesstoken))
            {
                throw new ArgumentNullException(nameof(accesstoken));
            }

            ParsedToken   = new System.IdentityModel.Tokens.Jwt.JwtSecurityToken(accesstoken);
            TokenAudience = Enums.TokenAudience.Other;
            AccessToken   = accesstoken;

            ExpiresOn = ParsedToken.ValidTo.ToLocalTime();
            Audiences = ParsedToken.Audiences.ToArray();
            TenantId  = Guid.TryParse(ParsedToken.Claims.FirstOrDefault(c => c.Type == "tid").Value, out Guid tenandIdGuid) ? (Guid?)tenandIdGuid : null;

            var rolesList = new List <string>();

            rolesList.AddRange(ParsedToken.Claims.Where(c => c.Type.Equals("roles", StringComparison.InvariantCultureIgnoreCase)).Select(c => c.Value));
            foreach (var scope in ParsedToken.Claims.Where(c => c.Type.Equals("scp", StringComparison.InvariantCultureIgnoreCase)))
            {
                rolesList.AddRange(scope.Value.Split(' '));
            }
            Roles = rolesList.ToArray();

            TokenType = ParsedToken.Claims.FirstOrDefault(c => c.Type == "upn") != null ? TokenType.Delegate : TokenType.Application;
        }
示例#10
0
        /// <summary>
        /// Renew the Azure AD token if it has expired.
        /// </summary>
        /// <param name="resourceUri">The token endpoint.</param>
        /// <param name="userPrincipalName">The AD username (AD).</param>
        /// <param name="userPassword">The AD password.</param>
        private void EnsureAzureADCredentialsToken(string resourceUri, string userPrincipalName, string userPassword)
        {
            if (this.AzureADToken == null)
            {
                lock (this.Lock)
                {
                    if (this.AzureADToken == null)
                    {
                        string accessToken = Task.Run(() => this.AcquireTokenAsync(resourceUri, userPrincipalName, userPassword)).GetAwaiter().GetResult();
                        ThreadPool.QueueUserWorkItem(obj =>
                        {
                            try
                            {
                                var token = new System.IdentityModel.Tokens.Jwt.JwtSecurityToken(accessToken);

                                var lease = GetAccessTokenLease(token.ValidTo);
                                lease     =
                                    TimeSpan.FromSeconds(lease.TotalSeconds - TimeSpan.FromMinutes(5).TotalSeconds > 0 ? lease.TotalSeconds - TimeSpan.FromMinutes(5).TotalSeconds : lease.TotalSeconds);
                                Thread.Sleep(lease);
                                this.AzureADToken = null;
                            }
                            catch (Exception)
                            {
                                this.AzureADToken = null;
                            }
                        });

                        this.AzureADToken = accessToken;
                    }
                }
            }
        }
示例#11
0
        private string ISecureDataFormat_Protect(AuthenticationTicket data)
        {
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }

            string audienceId = AppConfiguration.GetByKey(GlobalLegaSys.ClientId);

            string symmetricKeyAsBase64 = AppConfiguration.GetByKey(GlobalLegaSys.ClientSecret);

            dynamic keyByteArray = TextEncodings.Base64Url.Decode(symmetricKeyAsBase64);

            dynamic signingKey = new HmacSigningCredentials(keyByteArray);

            dynamic issued = data.Properties.IssuedUtc;

            dynamic expires = data.Properties.ExpiresUtc;

            dynamic token = new System.IdentityModel.Tokens.Jwt.JwtSecurityToken(_issuer, audienceId, data.Identity.Claims, issued.UtcDateTime, expires.UtcDateTime, signingKey);

            dynamic handler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler();

            dynamic jwt = handler.WriteToken(token);

            return(jwt);
        }
示例#12
0
        private static TimeSpan CalculateThreadSleep(string accessToken)
        {
            var token = new System.IdentityModel.Tokens.Jwt.JwtSecurityToken(accessToken);
            var lease = GetAccessTokenLease(token.ValidTo);

            lease = TimeSpan.FromSeconds(lease.TotalSeconds - TimeSpan.FromMinutes(5).TotalSeconds > 0 ? lease.TotalSeconds - TimeSpan.FromMinutes(5).TotalSeconds : lease.TotalSeconds);
            return(lease);
        }
示例#13
0
        public ActionResult ImplicitLanding()
        {
            logger.Debug("ImplicitLanding");
            System.IdentityModel.Tokens.Jwt.JwtSecurityToken tokenReceived = new System.IdentityModel.Tokens.Jwt.JwtSecurityToken();

            TempData["oktaOrg"] = MvcApplication.apiUrl;

            return(View("ImtokenReceivedplicitLanding", tokenReceived));
        }
示例#14
0
        // GET: api/CustomAPI
        public async Task <IEnumerable <string> > Get(String spoResourceUri)
        {
            var apiResult = new List <String>();

            // Read the OAuth settings
            var tenantId     = ConfigurationManager.AppSettings["ida:TenantId"];
            var clientId     = ConfigurationManager.AppSettings["ida:ClientId"];
            var clientSecret = ConfigurationManager.AppSettings["ida:ClientSecret"];
            // var spoResourceUri = ConfigurationManager.AppSettings["SPOResourceURI"];

            // Save the current username in the response
            var currentUsername = System.Threading.Thread.CurrentPrincipal?.Identity?.Name;

            apiResult.Add(currentUsername);

            // Get an access token on-behalf-of to consume SPO from this API
            var tokenRequestUrl = $"https://login.microsoftonline.com/common/oauth2/token";

            using (var client = new HttpClient())
            {
                // Prepare the request parameters
                var content = new FormUrlEncodedContent(new[]
                {
                    new KeyValuePair <string, string>("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer"),
                    new KeyValuePair <string, string>("client_id", clientId),
                    new KeyValuePair <string, string>("client_secret", clientSecret),
                    new KeyValuePair <string, string>("assertion", Request.Headers.Authorization.Parameter),
                    new KeyValuePair <string, string>("resource", spoResourceUri),
                    new KeyValuePair <string, string>("requested_token_use", "on_behalf_of"),
                });

                // Make the token request
                var result = await client.PostAsync(tokenRequestUrl, content);

                string jsonToken = await result.Content.ReadAsStringAsync();

                // Get back the OAuth 2.0 response
                var token = JsonConvert.DeserializeObject <OAuthTokenResponse>(jsonToken);

                // Retrieve and deserialize into a JWT token the Access Token
                var jwtAccessToken = new System.IdentityModel.Tokens.Jwt.JwtSecurityToken(token.AccessToken);

                // Make a request to SPO using the retrieved Access Token
                var spoJsonResponse = HttpHelper.MakeGetRequestForString(
                    $"{spoResourceUri}_api/web/CurrentUser?$select=Id,LoginName,Title",
                    "application/json",
                    token.AccessToken);

                apiResult.Add(spoJsonResponse);
            }

            // This API will simply use SPO in the back-end to get a list o site collections
            return(apiResult);
        }
        internal static SPOnlineConnection InstantiateGraphAccessTokenConnection(string accessToken, PSHost host, bool disableTelemetry)
        {
            var jwtToken    = new System.IdentityModel.Tokens.Jwt.JwtSecurityToken(accessToken);
            var tokenResult = new TokenResult();

            tokenResult.AccessToken = accessToken;
            tokenResult.ExpiresOn   = jwtToken.ValidTo;
            var spoConnection = new SPOnlineConnection(tokenResult, ConnectionMethod.AccessToken, ConnectionType.O365, 0, 0, 0, PnPPSVersionTag, host, disableTelemetry, InitializationType.Graph);

            spoConnection.ConnectionMethod = ConnectionMethod.GraphDeviceLogin;
            return(spoConnection);
        }
        private string GetToken(Claim[] claims)
        {
            var key    = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:Key"]));
            var signIn = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var token  = new System.IdentityModel.Tokens.Jwt.JwtSecurityToken(
                _configuration["Jwt:Issuer"],
                _configuration["Jwt:Audience"],
                claims,
                expires: DateTime.UtcNow.AddDays(1),
                signingCredentials: signIn);

            return(new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler().WriteToken(token));
        }
示例#17
0
        public string GenerateJSONWebToken(User user)
        {
            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
            var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

            var token = new System.IdentityModel.Tokens.Jwt.JwtSecurityToken(_config["Jwt:Issuer"],
                                                                             _config["Jwt:Issuer"],
                                                                             null,
                                                                             expires: DateTime.Now.AddMinutes(2),
                                                                             signingCredentials: credentials);

            return(new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler().WriteToken(token));
        }
示例#18
0
        private string GenerateJSONWebToken(Models.UserModel userInfo)
        {
            var securityKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
            var credentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(securityKey, Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256);

            var token = new System.IdentityModel.Tokens.Jwt.JwtSecurityToken(_config["Jwt:Issuer"],
                                                                             _config["Jwt:Issuer"],
                                                                             null,
                                                                             expires: DateTime.Now.AddMinutes(120),
                                                                             signingCredentials: credentials);

            return(new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler().WriteToken(token));
        }
        internal static SPOnlineConnection InstantiateGraphAccessTokenConnection(string accessToken)
        {
#if NETSTANDARD2_0
            var jwtToken = new System.IdentityModel.Tokens.Jwt.JwtSecurityToken(accessToken);
#else
            var jwtToken = new System.IdentityModel.Tokens.JwtSecurityToken(accessToken);
#endif
            var tokenResult = new TokenResult();
            tokenResult.AccessToken = accessToken;
            tokenResult.ExpiresOn   = jwtToken.ValidTo;
            var spoConnection = new SPOnlineConnection(tokenResult, ConnectionMethod.AccessToken, ConnectionType.O365, 0, 0, 0, PnPPSVersionTag);
            spoConnection.ConnectionMethod = ConnectionMethod.GraphDeviceLogin;
            return(spoConnection);
        }
示例#20
0
        protected System.Security.Claims.ClaimsPrincipal ValidateJwtToken(
            string jwtToken
            , out Microsoft.IdentityModel.Tokens.SecurityToken token)
        {
            System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler tokenHandler =
                new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler();

            // Parse JWT from the Base64UrlEncoded wire form
            // (<Base64UrlEncoded header>.<Base64UrlEncoded body>.<signature>)
            System.IdentityModel.Tokens.Jwt.JwtSecurityToken parsedJwt = tokenHandler.ReadToken(jwtToken)
                                                                         as System.IdentityModel.Tokens.Jwt.JwtSecurityToken;

            return(tokenHandler.ValidateToken(jwtToken, this.m_validationParameters, out token));
        } // End Function ValidateJwtToken
示例#21
0
        private string GetToken()
        {
            var currentToken = new System.IdentityModel.Tokens.Jwt.JwtSecurityToken(token);

            if (currentToken.ValidTo - DateTime.UtcNow < TimeSpan.FromSeconds(10))
            {
                token = tokenGenerator.Generate();
            }
            if (DateTime.UtcNow - currentToken.ValidFrom < TimeSpan.FromSeconds(1))
            {
                Task.Delay(1000);
            }
            return(token);
        }
示例#22
0
        internal static PnPConnection InstantiateSPOnlineConnection(Uri url, PSCredential credentials, string tenantAdminUrl, bool disableTelemetry, AzureEnvironment azureEnvironment = AzureEnvironment.Production)
        {
            var context = new PnPClientContext(url.AbsoluteUri)
            {
                ApplicationName         = Resources.ApplicationName,
                DisableReturnValueCache = true
            };
            var tenantId = string.Empty;

            try
            {
                using (var authManager = new PnP.Framework.AuthenticationManager(credentials.UserName, credentials.Password))
                {
                    context = PnPClientContext.ConvertFrom(authManager.GetContext(url.ToString()));
                    context.ExecuteQueryRetry();

                    var accessToken = authManager.GetAccessTokenAsync(url.ToString()).GetAwaiter().GetResult();
                    var parsedToken = new System.IdentityModel.Tokens.Jwt.JwtSecurityToken(accessToken);
                    tenantId = parsedToken.Claims.FirstOrDefault(c => c.Type == "tid").Value;
                }
            }
            catch (ClientRequestException)
            {
                context.Credentials = new NetworkCredential(credentials.UserName, credentials.Password);
            }
            catch (ServerException)
            {
                context.Credentials = new NetworkCredential(credentials.UserName, credentials.Password);
            }
            var connectionType = ConnectionType.O365;

            if (url.Host.ToLowerInvariant().EndsWith($"sharepoint.{PnP.Framework.AuthenticationManager.GetSharePointDomainSuffix(azureEnvironment)}"))
            {
                connectionType = ConnectionType.O365;
            }

            if (IsTenantAdminSite(context))
            {
                connectionType = ConnectionType.TenantAdmin;
            }
            var spoConnection = new PnPConnection(context, connectionType, credentials, url.ToString(), tenantAdminUrl, PnPPSVersionTag, disableTelemetry, InitializationType.Credentials)
            {
                ConnectionMethod = Model.ConnectionMethod.Credentials,
                AzureEnvironment = azureEnvironment,
                Tenant           = tenantId
            };

            return(spoConnection);
        }
示例#23
0
        public Task <UserClaim> Handle(TokenGenerateQuery request, CancellationToken cancellationToken)
        {
            UserClaim GenerateToken(UserViewModel userViewModel)
            {
                var now = DateTime.UtcNow;

                var claims = new Claim[]
                {
                    new Claim(JwtRegisteredClaimNames.Sub, userViewModel.Name),
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                    new Claim(JwtRegisteredClaimNames.Iat, now.ToUniversalTime().ToString(), ClaimValueTypes.Integer64)
                };

                var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(settings.Value.Secret));
                var tokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = signingKey,
                    ValidateIssuer           = true,
                    ValidIssuer           = settings.Value.Iss,
                    ValidateAudience      = true,
                    ValidAudience         = settings.Value.Aud,
                    ValidateLifetime      = true,
                    ClockSkew             = TimeSpan.Zero,
                    RequireExpirationTime = true,
                };

                var jwt = new System.IdentityModel.Tokens.Jwt.JwtSecurityToken(
                    issuer: settings.Value.Iss,
                    audience: settings.Value.Aud,
                    claims: claims,
                    notBefore: now,
                    expires: now.Add(TimeSpan.FromMinutes(24 * 60)),
                    signingCredentials: new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256)
                    );
                var encodedJwt = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler().WriteToken(jwt);
                var userClaims = mapper.Map <UserClaim>(userViewModel);

                userClaims.Token     = encodedJwt;
                userClaims.ExpiresIn = (int)TimeSpan.FromMinutes(2).TotalSeconds;

                return(userClaims);
            }

            var userClaim = GenerateToken(request.UserViewModel);

            return(Task.FromResult(userClaim));
        }
        // GET api/values
        public IEnumerable <string> Get()
        {
            // To Read Claims on Api Controller
            var jwt     = Request.Headers.Authorization.Parameter;
            var handler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler();

            System.IdentityModel.Tokens.Jwt.JwtSecurityToken token = handler.ReadJwtToken(jwt);

            IEnumerable <Claim> claims = token.Claims.ToList();

            string id       = token.Claims.FirstOrDefault(x => x.Type == "id").Value;
            string role     = token.Claims.FirstOrDefault(x => x.Type == "role").Value;
            string Compcode = token.Claims.FirstOrDefault(x => x.Type == "Compcode").Value;
            string Bracode  = token.Claims.FirstOrDefault(x => x.Type == "Bracode").Value;

            return(new string[] { "value1", "value2" });
        }
        public static bool TryParseJwt(this IHttpRequest request,
                                       out System.IdentityModel.Tokens.Jwt.JwtSecurityToken securityToken)
        {
            securityToken = default;
            var jwtString = request.GetAuthorization();

            if (jwtString.IsNullOrWhiteSpace())
            {
                return(false);
            }

            var kvp = jwtString.ParseJwtString(
                st => st.PairWithKey(true),
                (why) => default);

            securityToken = kvp.Value;
            return(kvp.Key);
        }
示例#26
0
        // /api/token/get
        public IActionResult Get(string appKey, string appPassword)
        {
            appKey      = "myKey";
            appPassword = "******";
            try
            {
                if (string.IsNullOrEmpty(appKey))
                {
                    throw new Exception("缺少appKey");
                }
                if (string.IsNullOrEmpty(appKey))
                {
                    throw new Exception("缺少appPassword");
                }
                if (appKey != "myKey" && appPassword != "myPassword")//固定的appKey及appPassword,实际项目中应该来自数据库或配置文件
                {
                    throw new Exception("配置不存在");
                }

                var key = new Microsoft.IdentityModel.Tokens
                          .SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(_configuration["JwtSecurityKey"]));
                var creds = new Microsoft.IdentityModel.Tokens
                            .SigningCredentials(key, Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256);
                var claims = new List <System.Security.Claims.Claim>();
                claims.Add(new System.Security.Claims.Claim("appKey", appKey)); //仅在Token中记录appKey
                var token = new System.IdentityModel.Tokens.Jwt.JwtSecurityToken(
                    issuer: _configuration["JwtTokenIssuer"],
                    audience: _configuration["JwtTokenAudience"],
                    claims: claims,
                    expires: DateTime.Now.AddMinutes(30),
                    signingCredentials: creds);

                return(Ok(new Models.ApiResponse {
                    status = 1, message = "OK", data = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler().WriteToken(token)
                }));
            }
            catch (Exception ex)
            {
                return(Ok(new Models.ApiResponse {
                    status = 0, message = ex.Message, data = ""
                }));
            }
        }
示例#27
0
        public string WriteToken()
        {
            var securityKey        = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_symetricSecurityKey));
            var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
            var header             = new System.IdentityModel.Tokens.Jwt.JwtHeader(signingCredentials);
            var payload            = new System.IdentityModel.Tokens.Jwt.JwtPayload {
                { ApplicationKeyKey, ApplicationKey }, { UserKey, UserName }
            };

            if (ExpirationDate.HasValue)
            {
                payload.Add(ExpirationKey, ExpirationDate.Value);
            }

            var jwt     = new System.IdentityModel.Tokens.Jwt.JwtSecurityToken(header, payload);
            var handler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler();

            return(handler.WriteToken(jwt));
        }
        protected override void LoadUserAuthInfo(AuthUserSession userSession, IAuthTokens tokens, Dictionary <string, string> authInfo)
        {
            var idAuthTokens = tokens as IdentityServerAuthTokens;

            if (!string.IsNullOrWhiteSpace(idAuthTokens?.IdToken))
            {
#if NETSTANDARD1_6
                var jwtToken = new System.IdentityModel.Tokens.Jwt.JwtSecurityToken(idAuthTokens.IdToken);
#elif NET45
                var jwtToken = new System.IdentityModel.Tokens.JwtSecurityToken(idAuthTokens.IdToken);
#endif
                idAuthTokens.Issuer  = jwtToken.Issuer;
                idAuthTokens.Subject = jwtToken.Subject;

                foreach (var claim in jwtToken.Claims)
                {
                    switch (claim.Type)
                    {
                    case JwtClaimTypes.Expiration:
                        idAuthTokens.Expiration = claim.Value;
                        break;

                    case JwtClaimTypes.Audience:
                        idAuthTokens.Audience = claim.Value;
                        break;

                    case JwtClaimTypes.IssuedAt:
                        idAuthTokens.IssuedAt = claim.Value;
                        break;

                    case JwtClaimTypes.AuthenticationTime:
                        idAuthTokens.AuthenticationTime = claim.Value;
                        break;

                    case JwtClaimTypes.Nonce:
                        idAuthTokens.Nonce = claim.Value;
                        break;
                    }
                }
            }

            base.LoadUserAuthInfo(userSession, tokens, authInfo);
        }
示例#29
0
        public string GenerateToken(Employee employee)
        {
            string key    = "my_secret_key_12345";
            var    issuer = "https://localhost:44363";

            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));
            var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

            var permClaims = new List <Claim>();

            permClaims.Add(new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()));
            permClaims.Add(new Claim(JwtRegisteredClaimNames.NameId, employee.ID.ToString()));
            permClaims.Add(new Claim(JwtRegisteredClaimNames.UniqueName, employee.Name));
            permClaims.Add(new Claim(JwtRegisteredClaimNames.Email, employee.Email));

            var token = new System.IdentityModel.Tokens.Jwt.JwtSecurityToken(issuer, issuer, permClaims, expires: DateTime.Now.AddDays(1), signingCredentials: credentials);

            return(new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler().WriteToken(token));
        }
示例#30
0
        protected void Page_Load(object sender, EventArgs e)
        {
            //取得返回的code
            var code = Request.QueryString["code"];

            if (code == null)
            {
                Response.Write("沒有正確回應code");
                Response.End();
            }
            //顯示,測試用
            Response.Write("<br/> code : " + code);
            //從Code取回toke
            var token = Utility.GetTokenFromCode(code,
                                                 "請更正為你自己的 client_id",                    //TODO:請更正為你自己的 client_id
                                                 "請更正為你自己的 client_secret",                //TODO:請更正為你自己的 client_secret
                                                 "http://localhost:17615/callback.aspx"); //TODO:請檢查此網址必須與你的LINE Login後台Call back URL相同

            //顯示,測試用(正式環境我們不會曝露token)
            Response.Write("<br/> token : " + token.access_token);
            //利用access_token取得用戶資料
            var user = Utility.GetUserProfile(token.access_token);
            //利用id_token取得Claim資料
            var JwtSecurityToken = new System.IdentityModel.Tokens.Jwt.JwtSecurityToken(token.id_token);
            var email            = "";

            //如果有email
            if (JwtSecurityToken.Claims.ToList().Find(c => c.Type == "email") != null)
            {
                email = JwtSecurityToken.Claims.First(c => c.Type == "email").Value;
            }

            //顯示,測試用
            Response.Write("<br/> user : "******"<br/> emal : " + email);
            //Response.End();

            //導入首頁,帶入token
            //(注意這是範例,token不該用明碼傳遞,也不該出現在用戶端,你應該自行記錄在資料庫或ServerSite session中)
            Response.Redirect($"default.aspx?token={HttpUtility.UrlEncode(token.access_token)}&email={email}");
        }