コード例 #1
0
 public void DemandModerator(JWTUser user)
 {
     if (!user.Claims.Contains("moderator"))
     {
         throw new Exception("Requires Moderator level status");
     }
 }
コード例 #2
0
 public void DemandAdmin(JWTUser user)
 {
     if (!user.Claims.Contains("admin"))
     {
         throw new Exception("Requires Admin level status");
     }
 }
コード例 #3
0
        public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
        {
            return(Task.Run(() =>
            {
                HttpRequestMessage request = context.Request;
                AuthenticationHeaderValue authorization = request.Headers.Authorization;
                //JsonResult<ErrorResponse> bad = new JsonResult<ErrorResponse>(new ErrorResponse(ErrorNumber.NOT_AUTHORIZED_FOR_OPERATION, "Generic not authorized"), new JsonSerializerSettings(), Encoding.ASCII, context.Request);

                if (authorization == null || authorization.Scheme != "Bearer")
                {
                    return;
                }

                if (String.IsNullOrEmpty(authorization.Parameter))
                {
                    context.ErrorResult = retError(ErrorNumber.INVALID_AUTHORIZATION_TOKEN_NO_BEARER, "No Bearer", request);
                    return;
                }

                JWTToken token = new JWTToken(authorization.Parameter);

                IPrincipal principal = new JWTUser(token);

                if (token.valid && !principal.Identity.IsAuthenticated)
                {
                    context.ErrorResult = retError(ErrorNumber.UNKNOWN_ERROR, "Not sure what this is", request);
                }
                else
                {
                    context.Principal = principal;
                }
                return;
            }));
        }
コード例 #4
0
        public HttpResponseMessage Get(string ticket, string version)
        {
            var api = Api.INSTANCE;

            if (ticket == null || ticket == "")
            {
                return(ERROR_MISSING_TOKEN());
            }

            using (var db = api.DAFactory.Get)
            {
                var dbTicket = db.AuthTickets.Get(ticket);
                if (dbTicket == null)
                {
                    return(ERROR_MISSING_TOKEN());
                }

                db.AuthTickets.Delete((string)ticket);
                if (dbTicket.date + api.Config.AuthTicketDuration < Epoch.Now)
                {
                    return(ERROR_EXPIRED_TOKEN());
                }

                /** Is it a valid account? **/
                var user = db.Users.GetById(dbTicket.user_id);
                if (user == null)
                {
                    return(ERROR_MISSING_TOKEN());
                }

                //Use JWT to create and sign an auth cookies
                var session = new JWTUser()
                {
                    UserID   = user.user_id,
                    UserName = user.username
                };

                //TODO: This assumes 1 shard, when using multiple need to either have version download occour after
                //avatar select, or rework the tables
                var shardOne = api.Shards.GetById(1);

                var token    = api.JWT.CreateToken(session);
                var response = ApiResponse.Xml(HttpStatusCode.OK, new UserAuthorized()
                {
                    FSOBranch    = shardOne.VersionName,
                    FSOVersion   = shardOne.VersionNumber,
                    FSOUpdateUrl = api.Config.UpdateUrl,
                    FSOCDNUrl    = api.Config.CDNUrl
                });

                var cookie = new CookieHeaderValue("fso", token.Token);
                cookie.Expires = DateTimeOffset.Now.AddDays(1);
                cookie.Domain  = Request.RequestUri.Host;
                cookie.Path    = "/";

                response.Headers.AddCookies(new CookieHeaderValue[] { cookie });
                //HttpContext.Current.Response.SetCookie(new HttpCookie("fso", token.Token));
                return(response);
            }
        }
コード例 #5
0
ファイル: JWTService.cs プロジェクト: tharin2002/httpgateway
        public static Task <ClaimsIdentity> CreateClaimsIdentities(JWTUser user)
        {
            ClaimsIdentity claimsIdentity = new ClaimsIdentity();

            claimsIdentity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.UserId));
            claimsIdentity.AddClaim(new Claim(ClaimTypes.Name, user.UserName));
            claimsIdentity.AddClaim(new Claim(ClaimTypes.Role, user.RoleId));
            return(Task.FromResult(claimsIdentity));
        }
コード例 #6
0
ファイル: JWTService.cs プロジェクト: tharin2002/httpgateway
        public async Task <string> Generate(JWTUser user, string privateKey)
        {
            var issuer    = "http://localhost";
            var authority = "http://localhost";
            var daysValid = 365;

            var createJwt = await CreateJWTAsync(user, issuer, authority, privateKey, daysValid);

            this.jwt = createJwt;
            return(createJwt);
        }
コード例 #7
0
ファイル: JWTService.cs プロジェクト: tharin2002/httpgateway
        public static async Task <string> CreateJWTAsync(
            JWTUser user,
            string issuer,
            string authority,
            string symSec,
            int daysValid)
        {
            var tokenHandler = new JwtSecurityTokenHandler();
            var claims       = await CreateClaimsIdentities(user);

            // Create JWToken
            var token = tokenHandler.CreateJwtSecurityToken(issuer: issuer,
                                                            audience: authority,
                                                            subject: claims,
                                                            notBefore: DateTime.UtcNow,
                                                            expires: DateTime.UtcNow.AddDays(daysValid),
                                                            signingCredentials:
                                                            new SigningCredentials(
                                                                new SymmetricSecurityKey(
                                                                    Encoding.Default.GetBytes(symSec)),
                                                                SecurityAlgorithms.HmacSha256Signature));

            return(tokenHandler.WriteToken(token));
        }
コード例 #8
0
        public HttpResponseMessage Post([FromBody] AuthRequest auth)
        {
            if (auth.grant_type == "password")
            {
                var api = Api.INSTANCE;
                using (var da = api.DAFactory.Get())
                {
                    var user = da.Users.GetByUsername(auth.username);
                    if (user == null || user.is_banned || !(user.is_admin || user.is_moderator))
                    {
                        return(ApiResponse.Json(System.Net.HttpStatusCode.OK, new OAuthError
                        {
                            error = "unauthorized_client",
                            error_description = "user_credentials_invalid"
                        }));
                    }

                    var authSettings      = da.Users.GetAuthenticationSettings(user.user_id);
                    var isPasswordCorrect = PasswordHasher.Verify(auth.password, new PasswordHash
                    {
                        data   = authSettings.data,
                        scheme = authSettings.scheme_class
                    });

                    if (!isPasswordCorrect)
                    {
                        return(ApiResponse.Json(System.Net.HttpStatusCode.OK, new OAuthError
                        {
                            error = "unauthorized_client",
                            error_description = "user_credentials_invalid"
                        }));
                    }

                    JWTUser identity = new JWTUser();
                    identity.UserName = user.username;
                    var claims = new List <string>();
                    if (user.is_admin || user.is_moderator)
                    {
                        claims.Add("moderator");
                    }
                    if (user.is_admin)
                    {
                        claims.Add("admin");
                    }

                    identity.Claims = claims;
                    identity.UserID = user.user_id;

                    var token = api.JWT.CreateToken(identity);

                    var response = ApiResponse.Json(System.Net.HttpStatusCode.OK, new OAuthSuccess
                    {
                        access_token = token.Token,
                        expires_in   = token.ExpiresIn
                    });

                    return(response);
                }
            }

            return(ApiResponse.Json(System.Net.HttpStatusCode.OK, new OAuthError
            {
                error = "invalid_request",
                error_description = "unknown grant_type"
            }));
        }
コード例 #9
0
        public IActionResult CreateToken([FromForm] UserOAuthRequest userAuthRequest)
        {
            if (userAuthRequest == null)
            {
                BadRequest();
            }
            var api = Api.INSTANCE;

            using (var da = api.DAFactory.Get())
            {
                var user = da.Users.GetByUsername(userAuthRequest.username);
                if (user == null || user.is_banned)
                {
                    return(ApiResponse.Json(System.Net.HttpStatusCode.Unauthorized, new UserOAuthError("unauthorized_client", "user_credentials_invalid")));
                }
                var ip                = ApiUtils.GetIP(Request);
                var hashSettings      = da.Users.GetAuthenticationSettings(user.user_id);
                var isPasswordCorrect = PasswordHasher.Verify(userAuthRequest.password, new PasswordHash
                {
                    data   = hashSettings.data,
                    scheme = hashSettings.scheme_class
                });
                //check if account is locked due to failed attempts
                var accLock = da.Users.GetRemainingAuth(user.user_id, ip);
                if (accLock != null && (accLock.active || accLock.count >= AuthLoginController.LockAttempts) && accLock.expire_time > Epoch.Now)
                {
                    return(ApiResponse.Json(System.Net.HttpStatusCode.OK, new UserOAuthError("unauthorized_client", "account_locked")));
                }
                //if the password is incorrect and check if user failed muli times and set a time out till next try.
                if (!isPasswordCorrect)
                {
                    var durations = AuthLoginController.LockDuration;
                    var failDelay = 60 * durations[Math.Min(durations.Length - 1, da.Users.FailedConsecutive(user.user_id, ip))];
                    if (accLock == null)
                    {
                        da.Users.NewFailedAuth(user.user_id, ip, (uint)failDelay);
                    }
                    else
                    {
                        var remaining = da.Users.FailedAuth(accLock.attempt_id, (uint)failDelay, AuthLoginController.LockAttempts);
                    }
                    return(ApiResponse.Json(System.Net.HttpStatusCode.OK, new UserOAuthError("unauthorized_client", "user_credentials_invalid")));
                }

                //user passed the password check, and now creates the claim/token
                da.Users.SuccessfulAuth(user.user_id, ip);
                var claims = new List <string>();

                //set the permission level in the claim
                switch (userAuthRequest.permission_level)
                {
                case 1:
                    claims.Add("userReadPermissions");
                    break;

                case 2:
                    claims.Add("userReadPermissions");
                    claims.Add("userWritePermissions");
                    break;

                case 3:
                    claims.Add("userReadPermissions");
                    claims.Add("userWritePermissions");
                    claims.Add("userUpdatePermissions");
                    break;

                case 4:
                    claims.Add("userReadPermissions");
                    claims.Add("userWritePermissions");
                    claims.Add("userUpdatePermissions");
                    claims.Add("userDeletePermissions");
                    break;

                default:
                    break;
                }

                //set the user identity
                JWTUser identity = new JWTUser
                {
                    UserID   = user.user_id,
                    UserName = user.username,
                    Claims   = claims
                };

                //generate the the tokenen and send it in a JSON format as response
                var generatedToken = api.JWT.CreateToken(identity);
                return(ApiResponse.Json(System.Net.HttpStatusCode.OK, new UserOAuthSuccess
                {
                    access_token = generatedToken.Token,
                    expires_in = generatedToken.ExpiresIn
                }));
            }
        }
コード例 #10
0
        public IActionResult Get(string ticket, string version)
        {
            var api = Api.INSTANCE;

            if (ticket == null || ticket == "" || version == null)
            {
                return(ERROR_MISSING_TOKEN());
            }

            using (var db = api.DAFactory.Get())
            {
                var dbTicket = db.AuthTickets.Get(ticket);
                if (dbTicket == null)
                {
                    return(ERROR_MISSING_TOKEN());
                }

                db.AuthTickets.Delete((string)ticket);
                if (dbTicket.date + api.Config.AuthTicketDuration < Epoch.Now)
                {
                    return(ERROR_EXPIRED_TOKEN());
                }

                /** Is it a valid account? **/
                var user = db.Users.GetById(dbTicket.user_id);
                if (user == null)
                {
                    return(ERROR_MISSING_TOKEN());
                }

                //Use JWT to create and sign an auth cookies
                var session = new JWTUser()
                {
                    UserID   = user.user_id,
                    UserName = user.username
                };

                //TODO: This assumes 1 shard, when using multiple need to either have version download occour after
                //avatar select, or rework the tables
                var shardOne = api.Shards.GetById(1);

                var token = api.JWT.CreateToken(session);

                IActionResult response;
                if (shardOne.UpdateID != null)
                {
                    var update = db.Updates.GetUpdate(shardOne.UpdateID.Value);
                    response = ApiResponse.Xml(HttpStatusCode.OK, new UserAuthorized()
                    {
                        FSOBranch    = shardOne.VersionName,
                        FSOVersion   = shardOne.VersionNumber,
                        FSOUpdateUrl = update.full_zip,
                        FSOCDNUrl    = api.Config.CDNUrl
                    });
                }
                else
                {
                    response = ApiResponse.Xml(HttpStatusCode.OK, new UserAuthorized()
                    {
                        FSOBranch    = shardOne.VersionName,
                        FSOVersion   = shardOne.VersionNumber,
                        FSOUpdateUrl = api.Config.UpdateUrl,
                        FSOCDNUrl    = api.Config.CDNUrl
                    });
                }
                Response.Cookies.Append("fso", token.Token, new Microsoft.AspNetCore.Http.CookieOptions()
                {
                    Expires = DateTimeOffset.Now.AddDays(1),
                    Domain  = Request.Host.Host,
                    Path    = "/"
                });
                //HttpContext.Current.Response.SetCookie(new HttpCookie("fso", token.Token));
                return(response);
            }
        }
コード例 #11
0
        public IActionResult Post([FromForm] AuthRequest auth)
        {
            if (auth == null)
            {
                Ok();
            }
            if (auth.grant_type == "password")
            {
                var api = Api.INSTANCE;
                using (var da = api.DAFactory.Get())
                {
                    var user = da.Users.GetByUsername(auth.username);
                    if (user == null || user.is_banned || !(user.is_admin || user.is_moderator))
                    {
                        return(ApiResponse.Json(System.Net.HttpStatusCode.OK, new OAuthError
                        {
                            error = "unauthorized_client",
                            error_description = "user_credentials_invalid"
                        }));
                    }

                    var ip      = ApiUtils.GetIP(Request);
                    var accLock = da.Users.GetRemainingAuth(user.user_id, ip);
                    if (accLock != null && (accLock.active || accLock.count >= AuthLoginController.LockAttempts) && accLock.expire_time > Epoch.Now)
                    {
                        return(ApiResponse.Json(System.Net.HttpStatusCode.OK, new OAuthError
                        {
                            error = "unauthorized_client",
                            error_description = "account_locked"
                        }));
                    }

                    var authSettings      = da.Users.GetAuthenticationSettings(user.user_id);
                    var isPasswordCorrect = PasswordHasher.Verify(auth.password, new PasswordHash
                    {
                        data   = authSettings.data,
                        scheme = authSettings.scheme_class
                    });

                    if (!isPasswordCorrect)
                    {
                        var durations = AuthLoginController.LockDuration;
                        var failDelay = 60 * durations[Math.Min(durations.Length - 1, da.Users.FailedConsecutive(user.user_id, ip))];
                        if (accLock == null)
                        {
                            da.Users.NewFailedAuth(user.user_id, ip, (uint)failDelay);
                        }
                        else
                        {
                            var remaining = da.Users.FailedAuth(accLock.attempt_id, (uint)failDelay, AuthLoginController.LockAttempts);
                        }

                        return(ApiResponse.Json(System.Net.HttpStatusCode.OK, new OAuthError
                        {
                            error = "unauthorized_client",
                            error_description = "user_credentials_invalid"
                        }));
                    }

                    da.Users.SuccessfulAuth(user.user_id, ip);

                    JWTUser identity = new JWTUser();
                    identity.UserName = user.username;
                    var claims = new List <string>();
                    if (user.is_admin || user.is_moderator)
                    {
                        claims.Add("moderator");
                    }
                    if (user.is_admin)
                    {
                        claims.Add("admin");
                    }

                    identity.Claims = claims;
                    identity.UserID = user.user_id;

                    var token = api.JWT.CreateToken(identity);

                    var response = ApiResponse.Json(System.Net.HttpStatusCode.OK, new OAuthSuccess
                    {
                        access_token = token.Token,
                        expires_in   = token.ExpiresIn
                    });

                    return(response);
                }
            }

            return(ApiResponse.Json(System.Net.HttpStatusCode.OK, new OAuthError
            {
                error = "invalid_request",
                error_description = "unknown grant_type"
            }));
        }