feat: allow to generate access token without expires time

This commit is contained in:
Steven 2023-08-07 19:52:13 +08:00
parent e855f8c5ad
commit dadf42c09b
5 changed files with 44 additions and 32 deletions

View File

@ -37,21 +37,21 @@ func GenerateAccessToken(username string, userID int32, expirationTime time.Time
// generateToken generates a jwt token. // generateToken generates a jwt token.
func generateToken(username string, userID int32, audience string, expirationTime time.Time, secret []byte) (string, error) { func generateToken(username string, userID int32, audience string, expirationTime time.Time, secret []byte) (string, error) {
// Create the JWT claims, which includes the username and expiry time. registeredClaims := jwt.RegisteredClaims{
claims := &ClaimsMessage{ Issuer: Issuer,
Name: username, Audience: jwt.ClaimStrings{audience},
RegisteredClaims: jwt.RegisteredClaims{ IssuedAt: jwt.NewNumericDate(time.Now()),
Issuer: Issuer, Subject: fmt.Sprint(userID),
Audience: jwt.ClaimStrings{audience}, }
// In JWT, the expiry time is expressed as unix milliseconds. if expirationTime.After(time.Now()) {
ExpiresAt: jwt.NewNumericDate(expirationTime), registeredClaims.ExpiresAt = jwt.NewNumericDate(expirationTime)
IssuedAt: jwt.NewNumericDate(time.Now()),
Subject: fmt.Sprint(userID),
},
} }
// Declare the token with the HS256 algorithm used for signing, and the claims. // Declare the token with the HS256 algorithm used for signing, and the claims.
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) token := jwt.NewWithClaims(jwt.SigningMethodHS256, &ClaimsMessage{
Name: username,
RegisteredClaims: registeredClaims,
})
token.Header["kid"] = KeyID token.Header["kid"] = KeyID
// Create the JWT string. // Create the JWT string.

View File

@ -17,9 +17,7 @@ import (
"google.golang.org/grpc/status" "google.golang.org/grpc/status"
) )
var authenticationAllowlistMethods = map[string]bool{ var authenticationAllowlistMethods = map[string]bool{}
"/memos.api.v2.UserService/GetUser": true,
}
// IsAuthenticationAllowed returns whether the method is exempted from authentication. // IsAuthenticationAllowed returns whether the method is exempted from authentication.
func IsAuthenticationAllowed(fullMethodName string) bool { func IsAuthenticationAllowed(fullMethodName string) bool {
@ -60,7 +58,7 @@ func (in *GRPCAuthInterceptor) AuthenticationInterceptor(ctx context.Context, re
} }
accessToken, err := getTokenFromMetadata(md) accessToken, err := getTokenFromMetadata(md)
if err != nil { if err != nil {
return nil, status.Errorf(codes.Unauthenticated, err.Error()) return nil, status.Errorf(codes.Unauthenticated, "failed to get access token from metadata: %v", err)
} }
userID, err := in.authenticate(ctx, accessToken) userID, err := in.authenticate(ctx, accessToken)
@ -71,11 +69,11 @@ func (in *GRPCAuthInterceptor) AuthenticationInterceptor(ctx context.Context, re
return nil, err return nil, err
} }
accessTokens, err := in.Store.GetUserAccessTokens(ctx, userID) userAccessTokens, err := in.Store.GetUserAccessTokens(ctx, userID)
if err != nil { if err != nil {
return nil, errors.Wrap(err, "failed to get user access tokens") return nil, errors.Wrap(err, "failed to get user access tokens")
} }
if !validateAccessToken(accessToken, accessTokens) { if !validateAccessToken(accessToken, userAccessTokens) {
return nil, status.Errorf(codes.Unauthenticated, "invalid access token") return nil, status.Errorf(codes.Unauthenticated, "invalid access token")
} }
@ -132,15 +130,16 @@ func (in *GRPCAuthInterceptor) authenticate(ctx context.Context, accessTokenStr
} }
func getTokenFromMetadata(md metadata.MD) (string, error) { func getTokenFromMetadata(md metadata.MD) (string, error) {
// Try to get the token from the authorization header first.
authorizationHeaders := md.Get("Authorization") authorizationHeaders := md.Get("Authorization")
if len(md.Get("Authorization")) > 0 { if len(authorizationHeaders) > 0 {
authHeaderParts := strings.Fields(authorizationHeaders[0]) authHeaderParts := strings.Fields(authorizationHeaders[0])
if len(authHeaderParts) != 2 || strings.ToLower(authHeaderParts[0]) != "bearer" { if len(authHeaderParts) != 2 || strings.ToLower(authHeaderParts[0]) != "bearer" {
return "", errors.Errorf("authorization header format must be Bearer {token}") return "", errors.Errorf("authorization header format must be Bearer {token}")
} }
return authHeaderParts[1], nil return authHeaderParts[1], nil
} }
// check the HTTP cookie // Try to get the token from the cookie header.
var accessToken string var accessToken string
for _, t := range append(md.Get("grpcgateway-cookie"), md.Get("cookie")...) { for _, t := range append(md.Get("grpcgateway-cookie"), md.Get("cookie")...) {
header := http.Header{} header := http.Header{}

View File

@ -9,6 +9,7 @@ import (
"github.com/boojack/slash/store" "github.com/boojack/slash/store"
"github.com/golang-jwt/jwt/v4" "github.com/golang-jwt/jwt/v4"
"github.com/pkg/errors" "github.com/pkg/errors"
"golang.org/x/exp/slices"
"google.golang.org/grpc/codes" "google.golang.org/grpc/codes"
"google.golang.org/grpc/status" "google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/timestamppb" "google.golang.org/protobuf/types/known/timestamppb"
@ -77,14 +78,21 @@ func (s *UserService) ListUserAccessTokens(ctx context.Context, request *apiv2pb
continue continue
} }
accessTokens = append(accessTokens, &apiv2pb.UserAccessToken{ userAccessToken := &apiv2pb.UserAccessToken{
AccessToken: userAccessToken.AccessToken, AccessToken: userAccessToken.AccessToken,
Description: userAccessToken.Description, Description: userAccessToken.Description,
IssuedAt: timestamppb.New(claims.IssuedAt.Time), IssuedAt: timestamppb.New(claims.IssuedAt.Time),
ExpiresAt: timestamppb.New(claims.ExpiresAt.Time), }
}) if claims.ExpiresAt != nil {
userAccessToken.ExpiresAt = timestamppb.New(claims.ExpiresAt.Time)
}
accessTokens = append(accessTokens, userAccessToken)
} }
// Sort by issued time in descending order.
slices.SortFunc(accessTokens, func(i, j *apiv2pb.UserAccessToken) bool {
return i.IssuedAt.Seconds > j.IssuedAt.Seconds
})
response := &apiv2pb.ListUserAccessTokensResponse{ response := &apiv2pb.ListUserAccessTokensResponse{
AccessTokens: accessTokens, AccessTokens: accessTokens,
} }
@ -133,13 +141,16 @@ func (s *UserService) CreateUserAccessToken(ctx context.Context, request *apiv2p
return nil, status.Errorf(codes.Internal, "failed to upsert access token to store: %v", err) return nil, status.Errorf(codes.Internal, "failed to upsert access token to store: %v", err)
} }
userAccessToken := &apiv2pb.UserAccessToken{
AccessToken: accessToken,
Description: request.UserAccessToken.Description,
IssuedAt: timestamppb.New(claims.IssuedAt.Time),
}
if claims.ExpiresAt != nil {
userAccessToken.ExpiresAt = timestamppb.New(claims.ExpiresAt.Time)
}
response := &apiv2pb.CreateUserAccessTokenResponse{ response := &apiv2pb.CreateUserAccessTokenResponse{
AccessToken: &apiv2pb.UserAccessToken{ AccessToken: userAccessToken,
AccessToken: accessToken,
Description: request.UserAccessToken.Description,
IssuedAt: timestamppb.New(claims.IssuedAt.Time),
ExpiresAt: timestamppb.New(claims.ExpiresAt.Time),
},
} }
return response, nil return response, nil
} }

View File

@ -25,8 +25,8 @@ const expirationOptions = [
value: 3600 * 24 * 7, value: 3600 * 24 * 7,
}, },
{ {
label: "Life time", label: "Never",
value: 3600 * 24 * 365 * 100, value: 0,
}, },
]; ];

View File

@ -95,7 +95,9 @@ const AccessTokenSection = () => {
{getFormatedAccessToken(userAccessToken.accessToken)} {getFormatedAccessToken(userAccessToken.accessToken)}
</td> </td>
<td className="whitespace-nowrap px-3 py-4 text-sm text-gray-500">{String(userAccessToken.issuedAt)}</td> <td className="whitespace-nowrap px-3 py-4 text-sm text-gray-500">{String(userAccessToken.issuedAt)}</td>
<td className="whitespace-nowrap px-3 py-4 text-sm text-gray-500">{String(userAccessToken.expiresAt)}</td> <td className="whitespace-nowrap px-3 py-4 text-sm text-gray-500">
{String(userAccessToken.expiresAt ?? "Never")}
</td>
<td className="relative whitespace-nowrap py-4 pl-3 pr-4 text-right text-sm font-medium"> <td className="relative whitespace-nowrap py-4 pl-3 pr-4 text-right text-sm font-medium">
<button <button
className="text-indigo-600 hover:text-indigo-900" className="text-indigo-600 hover:text-indigo-900"