Skip to content

Commit

Permalink
code refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
ZhongjunTian committed May 19, 2017
1 parent 29ab31d commit 6e98461
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 21 deletions.
1 change: 0 additions & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
Expand Down
19 changes: 11 additions & 8 deletions src/main/java/hello/Application.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,12 @@
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static hello.JwtUtil.HEADER_STRING;
import static hello.JwtUtil.TOKEN_PREFIX;

/*
https://auth0.com/blog/securing-spring-boot-with-jwts/
https://github.com/auth0-blog/spring-boot-jwts
Expand All @@ -34,20 +36,21 @@ public class Application {
@Bean
public FilterRegistrationBean jwtFilter() {
final FilterRegistrationBean registrationBean = new FilterRegistrationBean();
JwtAuthenticationFilter filter = new JwtAuthenticationFilter();
filter.setExcludeUrlPatterns("/*.html", "/", "/login","/public");
JwtAuthenticationFilter filter = new JwtAuthenticationFilter(
"/*.html", "/", "/login","/public");
registrationBean.setFilter(filter);
return registrationBean;
}

@PostMapping("/login")
public void login(HttpServletRequest request, HttpServletResponse response,
@RequestBody final AccountCredentials credentials) throws IOException {
public void login(HttpServletResponse response,
@RequestBody final AccountCredentials credentials) throws IOException {
//here we just have one hardcoded username=admin and password=admin
//TODO add your own user validation code here
if(validCredentials(credentials))
TokenAuthUtil.addTokenToHeader(response,credentials.username);
else
if(validCredentials(credentials)) {
String jwt = JwtUtil.generateToken(credentials.username);
response.addHeader(HEADER_STRING, TOKEN_PREFIX + " " + jwt);
}else
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Wrong credentials");
}

Expand Down
16 changes: 11 additions & 5 deletions src/main/java/hello/JwtAuthenticationFilter.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,26 @@
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

import static hello.JwtUtil.HEADER_STRING;

public class JwtAuthenticationFilter extends OncePerRequestFilter {
List<String> excludeUrlPatterns;
List<String> excludeUrlPatterns = new LinkedList<>();
PathMatcher pathMatcher = new AntPathMatcher();

public JwtAuthenticationFilter(String... excludeUrlPatterns) {
this.excludeUrlPatterns.addAll(
Arrays.asList(excludeUrlPatterns));
}

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

try {
String username = TokenAuthUtil.validateToken(request);
String token = request.getHeader(HEADER_STRING);
JwtUtil.validateToken(token);
} catch (Exception e) {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, e.getMessage());
return;
Expand All @@ -34,7 +43,4 @@ protected boolean shouldNotFilter(HttpServletRequest request) throws ServletExce
.anyMatch(p -> pathMatcher.match(p, request.getServletPath()));
}

public void setExcludeUrlPatterns(String... excludeUrlPatterns) {
this.excludeUrlPatterns = Arrays.asList(excludeUrlPatterns);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,31 +4,29 @@
import io.jsonwebtoken.SignatureAlgorithm;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class TokenAuthUtil {
public class JwtUtil {
static final long EXPIRATION_TIME = 3600_000; // 1 hour
static final String SECRET = "ThisIsASecret";
static final String TOKEN_PREFIX = "Bearer";
static final String HEADER_STRING = "Authorization";

public static void addTokenToHeader(HttpServletResponse res, String username) {
public static String generateToken(String username) {
HashMap<String, Object> map = new HashMap<>();
//you can put any data in the map
map.put("username", username);
String JWT = Jwts.builder()
String jwt = Jwts.builder()
.setClaims(map)
.setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
.signWith(SignatureAlgorithm.HS512, SECRET)
.compact();
res.addHeader(HEADER_STRING, TOKEN_PREFIX + " " + JWT);
return jwt;
}

public static String validateToken(HttpServletRequest request) {
String token = request.getHeader(HEADER_STRING);
public static String validateToken(String token) {
if (token != null) {
// parse the token.
Map<String,Object> body = Jwts.parser()
Expand Down

0 comments on commit 6e98461

Please sign in to comment.