-
Notifications
You must be signed in to change notification settings - Fork 2
/
AuthController.cs
125 lines (106 loc) · 4.53 KB
/
AuthController.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
using Locker.Api.Features.Auth.Models;
using Locker.Api.Features.Shared;
using Locker.Api.Web.Filters;
using Locker.Domain.Features.Auth.Entities;
using Locker.Domain.Features.Auth.Repositories;
using Locker.Domain.Features.Shared.ExecutionResult;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
namespace Locker.Api.Features.Auth
{
[ValidateModelStateFilter]
public class AuthController : Controller
{
private readonly IUserRepository _userRepository;
private readonly IAuthService _authService;
public AuthController(
IUserRepository userRepository,
IAuthService authService)
{
_userRepository = userRepository;
_authService = authService;
}
private IEnumerable<Claim> GetUserClaims(User user) =>
user.Permissions.GroupBy(it => it.Resource).Select(group =>
new Claim(@group.Key, string.Join(',', @group.Select(it => it.AccessRight))))
.Concat(new[] { new Claim(ClaimTypes.NameIdentifier, user.Id) });
[AllowAnonymous, HttpPost("api/auth/token")]
public Task<IActionResult> GetToken([BindRequired, FromBody] GetAuthTokenApiInput input)
{
if (input.GrantType == "password")
{
return GetTokenViaPasswordGrantType(input.UserName, input.Password);
}
if (input.GrantType == "refresh_token")
{
return GetTokenViaRefreshTokenGrantType(input.AccessToken, input.RefreshToken);
}
throw new NotSupportedException($"{input.GrantType} is not supported.");
}
[NonAction]
public async Task<IActionResult> GetTokenViaPasswordGrantType(string userName, string password)
{
var user = await _userRepository.FindByUsername(userName).ConfigureAwait(false);
if (user == null || !user.PasswordsMatch(password))
{
return new ExecutionResult
{
ResultType = ExecutionResultType.ValidationError,
Message = "Invalid username or password."
}.ToActionResult();
}
var accessToken = _authService.GenerateAccessToken(GetUserClaims(user));
var refreshToken = _authService.GenerateRefreshToken();
await _userRepository.AddRefreshToken(user.Id, refreshToken).ConfigureAwait(false);
return new ExecutionResult<TokenApiOutput>
{
ResultType = ExecutionResultType.Ok,
Value = new TokenApiOutput
{
AccessToken = accessToken,
RefreshToken = refreshToken
}
}.ToActionResult();
}
[NonAction]
public async Task<IActionResult> GetTokenViaRefreshTokenGrantType(string accessToken, string refreshToken)
{
var claimsPrincipal = _authService.ReadClaimsPrincipalFromExpiredToken(accessToken);
if (claimsPrincipal == null)
{
return new ExecutionResult
{
ResultType = ExecutionResultType.ValidationError,
Message = "Invalid access token."
}.ToActionResult();
}
var userId = claimsPrincipal.Claims.First(it => it.Type == ClaimTypes.NameIdentifier).Value;
if (!await _userRepository.TryUseRefreshToken(userId, refreshToken).ConfigureAwait(false))
{
return new ExecutionResult
{
ResultType = ExecutionResultType.ValidationError,
Message = "Invalid refresh token."
}.ToActionResult();
}
var newRefreshToken = _authService.GenerateRefreshToken();
await _userRepository.AddRefreshToken(userId, newRefreshToken).ConfigureAwait(false);
var user = await _userRepository.Get(userId).ConfigureAwait(false);
return new ExecutionResult<TokenApiOutput>
{
ResultType = ExecutionResultType.Ok,
Value = new TokenApiOutput
{
AccessToken = _authService.GenerateAccessToken(GetUserClaims(user)),
RefreshToken = newRefreshToken
}
}.ToActionResult();
}
}
}