Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/resolve #25

Merged
merged 4 commits into from
Jun 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,11 @@
import io.wwan13.wintersecurity.auth.RequestStorage;
import io.wwan13.wintersecurity.auth.TokenExtractor;
import io.wwan13.wintersecurity.constant.Constants;
import io.wwan13.wintersecurity.jwt.TokenClaims;
import io.wwan13.wintersecurity.jwt.TokenDecoder;
import io.wwan13.wintersecurity.jwt.payload.util.RoleSerializer;
import org.springframework.http.HttpMethod;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

public class InterceptorAuthProcessor extends AbstractInterceptorAuthProcessor {

Expand Down Expand Up @@ -57,16 +56,15 @@ private void actionIfTokenPresent(
HttpServletRequest request,
RequestStorage storage
) {
Map<String, Object> claims = tokenDecoder.decode(token);
String rawRoles = (String) claims.get(Constants.PAYLOAD_KEY_USER_ROLE);
TokenClaims claims = tokenDecoder.decode(token);

accessManager.manageWithAuthentication(
HttpMethod.resolve(request.getMethod()),
request.getRequestURI(),
RoleSerializer.deserialize(rawRoles)
claims.getRoles()
);

storage.saveAll(claims);
storage.save(Constants.ATTRIBUTE_CLAIMS_KEY, claims);
}

private void actionIfTokenAbsent(HttpServletRequest request) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@ public class Constants {
public static final String PAYLOAD_KEY_USER_ROLE = "roles";
public static final String DEFAULT_SUBJECT_KEY = "sub";

// Attribute
public static final String ATTRIBUTE_CLAIMS_KEY = "claims";

// Token
public static final String TOKEN_TYPE_ACCESS = "access_token";
public static final String TOKEN_TYPE_REFRESH = "refresh_token";
Expand Down
65 changes: 65 additions & 0 deletions src/main/java/io/wwan13/wintersecurity/jwt/TokenClaims.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
/*
* Copyright 2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package io.wwan13.wintersecurity.jwt;

import io.wwan13.wintersecurity.constant.Constants;
import io.wwan13.wintersecurity.jwt.payload.util.RoleSerializer;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

public record TokenClaims(
Map<String, Object> claims
) {

public Object getSubject() {
return getValueWithNullChecking(Constants.DEFAULT_SUBJECT_KEY);
}

public Set<String> getRoles() {
String rawRoles = (String) getValueWithNullChecking(Constants.PAYLOAD_KEY_USER_ROLE);
return RoleSerializer.deserialize(rawRoles);
}

public boolean isAccessToken() {
String tokenType = (String) getValueWithNullChecking(Constants.PAYLOAD_KEY_TOKEN_TYPE);
return Constants.TOKEN_TYPE_ACCESS.equals(tokenType);
}

public boolean isRefreshToken() {
String tokenType = (String) getValueWithNullChecking(Constants.PAYLOAD_KEY_TOKEN_TYPE);
return Constants.TOKEN_TYPE_REFRESH.equals(tokenType);
}

public Object get(String key) {
return getValueWithNullChecking(key);
}

public Map<String, Object> toMap() {
return new HashMap<>(claims);
}

private Object getValueWithNullChecking(String key) {
Object value = claims.get(key);
if (Objects.isNull(value)) {
throw new IllegalArgumentException(key + "not exists at token claims");
}
return value;
}
}
4 changes: 1 addition & 3 deletions src/main/java/io/wwan13/wintersecurity/jwt/TokenDecoder.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,6 @@

package io.wwan13.wintersecurity.jwt;

import java.util.Map;

public interface TokenDecoder {
Map<String, Object> decode(String token);
TokenClaims decode(String token);
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import io.jsonwebtoken.*;
import io.wwan13.wintersecurity.exception.unauthirized.ExpiredJwtTokenException;
import io.wwan13.wintersecurity.exception.unauthirized.InvalidJwtTokenException;
import io.wwan13.wintersecurity.jwt.TokenClaims;
import io.wwan13.wintersecurity.jwt.TokenDecoder;
import io.wwan13.wintersecurity.secretkey.SecretKey;

Expand All @@ -34,8 +35,9 @@ public JwtTokenDecoder(SecretKey secretKey) {
}

@Override
public Map<String, Object> decode(String token) {
return parseClaimsWithExceptionHandling(token);
public TokenClaims decode(String token) {
Map<String, Object> claims = parseClaimsWithExceptionHandling(token);
return new TokenClaims(claims);
}

public Claims parseClaimsWithExceptionHandling(String token) {
Expand Down

This file was deleted.

This file was deleted.

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,6 @@

public record TargetAnnotations(
Set<Class<? extends Annotation>> forSubject,
Set<Class<? extends Annotation>> forRoles,
Set<Class<? extends Annotation>> forClaims,
Set<Class<? extends Annotation>> forClaim,
Set<Class<? extends Annotation>> forPayload
Set<Class<? extends Annotation>> forRoles
) {
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,25 +28,13 @@ public class TargetAnnotationsRegistry {
= Set.of(RequestUserSubject.class, RequestUserId.class);
private final static Set<Class<? extends Annotation>> DEFAULT_ROLES_TARGETS
= Set.of(RequestUserRoles.class);
private final static Set<Class<? extends Annotation>> DEFAULT_CLAIMS_TARGETS
= Set.of(RequestUserClaims.class);
private final static Set<Class<? extends Annotation>> DEFAULT_CLAIM_TARGETS
= Set.of(RequestUserClaim.class);
private final static Set<Class<? extends Annotation>> DEFAULT_PAYLOAD_TARGETS
= Set.of(RequestUserPayload.class);

private final Set<Class<? extends Annotation>> forSubject;
private final Set<Class<? extends Annotation>> forRoles;
private final Set<Class<? extends Annotation>> forClaims;
private final Set<Class<? extends Annotation>> forClaim;
private final Set<Class<? extends Annotation>> forPayload;

public TargetAnnotationsRegistry() {
this.forSubject = new HashSet<>(DEFAULT_SUBJECT_TARGETS);
this.forRoles = new HashSet<>(DEFAULT_ROLES_TARGETS);
this.forClaims = new HashSet<>(DEFAULT_CLAIMS_TARGETS);
this.forClaim = new HashSet<>(DEFAULT_CLAIM_TARGETS);
this.forPayload = new HashSet<>(DEFAULT_PAYLOAD_TARGETS);
}

public TargetAnnotationsRegistry addSubjectResolveAnnotation(
Expand All @@ -63,28 +51,7 @@ public TargetAnnotationsRegistry addRolesResolveAnnotation(
return this;
}

public TargetAnnotationsRegistry addClaimsResolveAnnotation(
Class<? extends Annotation> target
) {
forClaims.add(target);
return this;
}

public TargetAnnotationsRegistry addClaimResolveAnnotation(
Class<? extends Annotation> target
) {
forClaim.add(target);
return this;
}

public TargetAnnotationsRegistry addPayloadResolveAnnotation(
Class<? extends Annotation> target
) {
forPayload.add(target);
return this;
}

protected TargetAnnotations apply() {
return new TargetAnnotations(forSubject, forRoles, forClaims, forClaim, forPayload);
return new TargetAnnotations(forSubject, forRoles);
}
}
95 changes: 95 additions & 0 deletions src/test/java/io/wwan13/wintersecurity/jwt/TokenClaimsTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
/*
* Copyright 2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package io.wwan13.wintersecurity.jwt;

import io.wwan13.wintersecurity.UnitTest;
import org.junit.jupiter.api.Test;

import java.util.Map;
import java.util.Set;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

class TokenClaimsTest extends UnitTest {

static final Map<String, Object> defaultClaims = Map.of(
"sub", "subject",
"roles", "ROLE_USER&ROLE_ADMIN",
"token_type", "refresh_token"
);

static final Map<String, Object> emptyClaims = Map.of();

@Test
void should_ContainsSubject() {
// given
final TokenClaims tokenClaims = new TokenClaims(defaultClaims);

// when
Object subject = tokenClaims.getSubject();

// then
assertThat((String) subject).isEqualTo(defaultClaims.get("sub"));
}

@Test
void should_ThrowException_when_SubjectNotExists() {
// given
final TokenClaims tokenClaims = new TokenClaims(emptyClaims);

// when, then
assertThatThrownBy(tokenClaims::getSubject)
.isInstanceOf(IllegalArgumentException.class);
}

@Test
void should_ContainsRoles() {
// given
final TokenClaims tokenClaims = new TokenClaims(defaultClaims);

// when
Set<String> subject = tokenClaims.getRoles();

// then
assertThat(subject).contains("ROLE_ADMIN", "ROLE_USER");
}

@Test
void should_ThrowException_when_RolesNotExists() {
// given
final TokenClaims tokenClaims = new TokenClaims(emptyClaims);

// when, then
assertThatThrownBy(tokenClaims::getRoles)
.isInstanceOf(IllegalArgumentException.class);
}

@Test
void should_JudgeTokenType() {
// given
final TokenClaims tokenClaims = new TokenClaims(defaultClaims);

// when
boolean isAccessToken = tokenClaims.isAccessToken();
boolean isRefreshToken = tokenClaims.isRefreshToken();

// then
assertThat(isAccessToken).isFalse();
assertThat(isRefreshToken).isTrue();
}
}
Loading
Loading