public async Task <AuthenticatedUserDto> AuthorizeAsync(LoginDto loginDto) { var userEntity = await _tripFlipDbContext .Users .AsNoTracking() .Include(user => user.ApplicationRoles) .ThenInclude(usersRoles => usersRoles.ApplicationRole) .FirstOrDefaultAsync(user => user.Email == loginDto.Email); EntityValidationHelper.ValidateEntityNotNull( userEntity, ErrorConstants.UserNotFound); bool isPasswordVerified = PasswordHasherHelper .VerifyPassword(loginDto.Password, userEntity.PasswordHash); if (!isPasswordVerified) { throw new ArgumentException(ErrorConstants.PasswordNotVerified); } AuthenticatedUserDto authenticatedUserDto = _mapper.Map <AuthenticatedUserDto>(userEntity); authenticatedUserDto.Token = JsonWebTokenHelper.GenerateJsonWebToken( userIncludingRoles: userEntity, issuer: _jwtConfiguration.Issuer, audience: _jwtConfiguration.Audience, secretKey: _jwtConfiguration.SecretKey, tokenLifetime: _jwtConfiguration.TokenLifetime); return(authenticatedUserDto); }
/// <summary> /// Is responsible for calling other methods that execute following actions: /// <list type="number"> /// <item>Exchanging given authorization code for id token.</item> /// <item>Obtaining user email from id token.</item> /// <item>Adding new user entry into database if user with the given email /// does not already exist.</item> /// <item>Generating new JWT token for the current user.</item> /// </list> /// </summary> /// <param name="authorizationCode">>A one-time authorization code provided by Google /// that is used to obtain Google's access token, ID token and refresh token.</param> /// <returns>A newly generated JWT.</returns> public async Task <string> LoginWithAuthCodeAsync(string authorizationCode) { await GetGoogleOpenIdConfigurationAsync(); var googleOauthResponse = await ExchangeAuthCodeForTokensAsync(authorizationCode); if (string.IsNullOrWhiteSpace(googleOauthResponse.AccessToken)) { throw new Exception(ErrorConstants.GoogleFailedToExchangeAuthCodeForTokens); } string userEmail = GetEmailFromGoogleIdToken(googleOauthResponse.IdToken); var userEntity = await GetUserByEmailAsync(userEmail); if (userEntity is null) { userEntity = await RegisterAsync(userEmail); } string jwt = JsonWebTokenHelper.GenerateJsonWebToken( userIncludingRoles: userEntity, issuer: _jwtConfiguration.Issuer, audience: _jwtConfiguration.Audience, secretKey: _jwtConfiguration.SecretKey, tokenLifetime: _jwtConfiguration.TokenLifetime); return(jwt); }
public async Task <User> Register(User user, string password) { byte[] passwordHash, passwordSalt; JsonWebTokenHelper.CreatePasswordHash(password, out passwordHash, out passwordSalt); user.PasswordHash = passwordHash; user.PasswordSalt = passwordSalt; await _users.InsertOneAsync(user); return(user); }
protected override void HandleUnauthorizedRequest(HttpActionContext actionContext) { Trace.TraceInformation("Enter JWT Authorize attribute."); if (actionContext == null) { throw new ArgumentNullException(Constants.Parameters.ActionContext); } var api = GetApi(actionContext.Request.RequestUri.LocalPath); Trace.TraceInformation($"localpath:{actionContext.Request.RequestUri.LocalPath}"); JsonWebTokenHelper helper = new JsonWebTokenHelper(new ConfigurationService(), api); Trace.TraceInformation("Call Getrequest object"); var request = helper.GetRequestObject(actionContext.Request); Trace.TraceInformation("GetRequestObject - success"); //presence of errors indicate bad request if (request.Errors != null && request.Errors.Count > 0) { Trace.TraceWarning("Bad Request Header: Error while parsing the request object"); actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized) { ReasonPhrase = Constants.Messages.JsonWebTokenParserError }; return; } //check token validation flags if (!request.HeaderAlgorithmValid || !request.HeaderTypeValid || !request.IssuedAtTimeValid || !request.NotBeforetimeValid || !request.SignatureValid || !request.ExpiryValid) { Trace.TraceWarning("Bad Request: One or more information is missing in the token or signature didn't match."); Trace.TraceWarning("Type:{0},Algorithm:{1},IatValid:{2},NbfValid:{3},SignValid:{4},Expiry:{5}" , request.HeaderTypeValid , request.HeaderAlgorithmValid , request.IssuedAtTimeValid , request.NotBeforetimeValid , request.SignatureValid , request.ExpiryValid); actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden) { ReasonPhrase = Constants.Messages.JsonWebTokenExpiredOrNoMatch }; return; } }
public async Task <User> Login(string username, string password) { var user = await _users.Find <User>(x => x.UserName == username).FirstOrDefaultAsync(); if (user == null) { return(null); } if (!JsonWebTokenHelper.VerifyPasswordHash(password, user.PasswordHash, user.PasswordSalt)) { return(null); } return(user); }
public override void OnAuthorization(HttpActionContext actionContext) { if (actionContext == null) { throw new ArgumentException("actionContext"); } HttpControllerContext context = actionContext.ControllerContext; if (context.Request.Headers.Authorization == null) { actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized) { Content = new StringContent("未授权访问") }; return; } var(isAuthorized, jwtIdentity) = JsonWebTokenHelper.ValidateToken(context.Request.Headers.Authorization.Parameter); if (!isAuthorized) { actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized) { Content = new StringContent("未授权访问") }; return; } Identity identity = new Identity(jwtIdentity.Name, context.Request.Headers.Authorization.Scheme, jwtIdentity.IsAuthenticated); PrincipalService p = new PrincipalService(); p.CreatePrincipal(identity); p.Role = ((ClaimsIdentity)jwtIdentity).Claims.ToList().Find(i => i.Type == ClaimTypes.Role).Value; if (!p.IsInRole()) { actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized) { Content = new StringContent("用户未授予身份资格") }; return; } context.RequestContext.Principal = p; base.OnAuthorization(actionContext); }
public ResponseMessage Get([FromQuery] string applicationName, long timeStamp, string signature) { if (string.IsNullOrWhiteSpace(applicationName)) { throw new Exception("applicationName不能为空"); } if (timeStamp <= 0) { throw new Exception("timeStamp不能为空"); } if (string.IsNullOrWhiteSpace(signature)) { throw new Exception("signature不能为空"); } string jwt = new JsonWebTokenHelper(_jwtOptions).GetJwt(applicationName, timeStamp, signature); return(new ResponseMessage(jwt)); }
public OAuthAccessToken GetAccessToken() { string stsUrl = "https://accounts.accesscontrol.windows.net/tokens/OAuth/2"; string AcsPrincipalId = "00000001-0000-0000-c000-000000000000"; // Service Principal ID for the graphService principal - this is a Universal (reserved) id for all tenants string protectedResourcePrincipalId = "00000002-0000-0000-c000-000000000000"; string protectedResourceHostName = "directory.windows.net"; var webToken = new JsonWebToken( this.spnAppPrincipalId, tenantId.ToString(), (new Uri(stsUrl)).DnsSafeHost, AcsPrincipalId, DateTime.Now.ToUniversalTime(), 60 * 60); string jwt = JsonWebTokenHelper.GenerateAssertion(webToken, this.spnSymmetricKey); string resource = String.Format("{0}/{1}@{2}", protectedResourcePrincipalId, protectedResourceHostName, tenantId); OAuthAccessToken accessToken = JsonWebTokenHelper.GetOAuthAccessTokenFromACS(stsUrl, jwt, resource); return(accessToken); }
public async Task <AuthorizedUserViewModel> LoginAsync(UserLoginViewModel userLoginViewModel) { var userEntity = await _context.Users .AsNoTracking() .FirstOrDefaultAsync(u => u.Login == userLoginViewModel.Login); bool isPasswordVerified = PasswordHasherHelper .VerifyPassword(userLoginViewModel.Password, userEntity.PasswordHash); if (!isPasswordVerified) { throw new ArgumentException(); } var token = JsonWebTokenHelper.GenerateJsonWebToken(userEntity.Id, userEntity.Login); var authorizedUserViewModel = new AuthorizedUserViewModel() { JwtToken = token, Email = userEntity.Login }; return(authorizedUserViewModel); }
public IHttpActionResult Token() { if (ModelState.IsValid)//判断是否合法 { //if (!(user == "abc" && password == "123456"))//判断账号密码是否正确 //{ // return BadRequest(); //} var tokenString = JsonWebTokenHelper.CreateToken("ff", "Admin"); return(Json(new { access_token = tokenString, token_type = "Bearer", createDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") })); } return(Json(new { err = "Not found", message = "Bad Request" })); }
private HttpResponseMessage ValidateMessage(Payload payload) { JsonWebTokenHelper helper = new JsonWebTokenHelper(this.configurationService, Api.Caching); var request = helper.GetRequestObject(payload); if (request.Errors != null && request.Errors.Count > 0) { Trace.TraceWarning("Bad Request Header: Error while parsing the request object"); return(new HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized) { ReasonPhrase = Constants.Messages.JsonWebTokenParserError }); } //check token validation flags if (!request.HeaderAlgorithmValid || !request.HeaderTypeValid || !request.IssuedAtTimeValid || !request.NotBeforetimeValid || !request.SignatureValid || !request.ExpiryValid) { Trace.TraceWarning("Bad Request: One or more information is missing in the token or signature didn't match."); Trace.TraceWarning("Type:{0},Algorithm:{1},IatValid:{2},NbfValid:{3},SignValid:{4},Expiry:{5}" , request.HeaderTypeValid , request.HeaderAlgorithmValid , request.IssuedAtTimeValid , request.NotBeforetimeValid , request.SignatureValid , request.ExpiryValid); return(new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden) { ReasonPhrase = Constants.Messages.JsonWebTokenExpiredOrNoMatch }); } return(null); }
public void TestSetup() { configurationService = new TestConfigurationService(); helper = new JsonWebTokenHelper(configurationService, Api.Booking); }