├── .gitignore
├── README.md
├── nbactions.xml
├── pom.xml
└── src
└── main
├── java
└── np
│ └── com
│ └── ngopal
│ └── spring
│ └── boot
│ └── redis
│ ├── Application.java
│ ├── config
│ ├── AuthenticationProviderImpl.java
│ ├── RedisConfig.java
│ └── SecurityConfiguration.java
│ ├── domain
│ ├── AuthenticationTokenImpl.java
│ └── SessionUser.java
│ ├── jwt
│ ├── JWTAuthenticationFilter.java
│ ├── JWTLoginFilter.java
│ └── TokenAuthenticationService.java
│ ├── resource
│ └── UserResource.java
│ └── service
│ └── RedisService.java
└── resources
├── application.properties
└── rebel.xml
/.gitignore:
--------------------------------------------------------------------------------
1 | /target/
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # spring-boot-redis-jwt
2 | Blog post: [Spring Boot with JWT authentication using Redis](http://blog.ngopal.com.np/2017/10/10/spring-boot-with-jwt-authentication-using-redis)
3 |
--------------------------------------------------------------------------------
/nbactions.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | run
5 |
6 | jar
7 |
8 |
9 | process-classes
10 | org.codehaus.mojo:exec-maven-plugin:1.2.1:exec
11 |
12 |
13 | -classpath %classpath np.com.ngopal.spring.boot.redis.Application
14 | java
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 4.0.0
4 | np.com.ngopal
5 | spring-boot-redis-jwt
6 | 1.0.0
7 | jar
8 |
9 | UTF-8
10 | 1.8
11 | 1.8
12 |
13 |
14 | org.springframework.boot
15 | spring-boot-starter-parent
16 | 1.5.7.RELEASE
17 |
18 |
19 |
20 | org.springframework.boot
21 | spring-boot-starter-web
22 |
23 |
24 | org.springframework.boot
25 | spring-boot-starter-data-redis
26 |
27 |
28 | org.springframework.boot
29 | spring-boot-starter-security
30 |
31 |
32 | io.jsonwebtoken
33 | jjwt
34 | 0.7.0
35 |
36 |
37 | org.projectlombok
38 | lombok
39 |
40 |
41 | redis.clients
42 | jedis
43 |
44 |
45 | spring-boot-redis-jwt
46 |
--------------------------------------------------------------------------------
/src/main/java/np/com/ngopal/spring/boot/redis/Application.java:
--------------------------------------------------------------------------------
1 | /*
2 | * To change this license header, choose License Headers in Project Properties.
3 | * To change this template file, choose Tools | Templates
4 | * and open the template in the editor.
5 | */
6 |
7 | package np.com.ngopal.spring.boot.redis;
8 |
9 | import com.fasterxml.jackson.databind.ObjectMapper;
10 | import np.com.ngopal.spring.boot.redis.jwt.TokenAuthenticationService;
11 | import np.com.ngopal.spring.boot.redis.service.RedisService;
12 | import org.springframework.beans.factory.annotation.Autowired;
13 | import org.springframework.beans.factory.annotation.Value;
14 | import org.springframework.boot.SpringApplication;
15 | import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
16 | import org.springframework.boot.autoconfigure.SpringBootApplication;
17 | import org.springframework.context.annotation.Bean;
18 |
19 | /**
20 | *
21 | * @author NGM
22 | */
23 | @SpringBootApplication
24 | @EnableAutoConfiguration
25 | public class Application {
26 |
27 | @Autowired
28 | private RedisService redisService;
29 |
30 | @Value("${ENC_KEY}")
31 | private String encKey;
32 |
33 | @Bean
34 | public TokenAuthenticationService tokenAuthService() {
35 | return new TokenAuthenticationService(redisService,encKey);
36 | }
37 |
38 | @Bean
39 | public ObjectMapper mapper(){
40 | return new ObjectMapper();
41 | }
42 |
43 | public static void main(String[] args) {
44 | SpringApplication.run(Application.class, args);
45 | }
46 |
47 | }
48 |
--------------------------------------------------------------------------------
/src/main/java/np/com/ngopal/spring/boot/redis/config/AuthenticationProviderImpl.java:
--------------------------------------------------------------------------------
1 | /*
2 | * To change this license header, choose License Headers in Project Properties.
3 | * To change this template file, choose Tools | Templates
4 | * and open the template in the editor.
5 | */
6 |
7 | package np.com.ngopal.spring.boot.redis.config;
8 |
9 | import java.util.Collections;
10 | import java.util.Date;
11 | import java.util.concurrent.TimeUnit;
12 | import np.com.ngopal.spring.boot.redis.domain.AuthenticationTokenImpl;
13 | import np.com.ngopal.spring.boot.redis.domain.SessionUser;
14 | import np.com.ngopal.spring.boot.redis.service.RedisService;
15 | import org.springframework.security.authentication.BadCredentialsException;
16 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
17 | import org.springframework.security.core.Authentication;
18 | import org.springframework.security.core.AuthenticationException;
19 |
20 | /**
21 | *
22 | * @author NGM
23 | */
24 | public class AuthenticationProviderImpl implements org.springframework.security.authentication.AuthenticationProvider {
25 |
26 | private RedisService service;
27 |
28 | public AuthenticationProviderImpl(RedisService service) {
29 | this.service = service;
30 | }
31 |
32 | @Override
33 | public Authentication authenticate(Authentication authentication) throws AuthenticationException {
34 | String username = authentication.getPrincipal() + "";
35 | String password = authentication.getCredentials() + "";
36 |
37 | if (username == null || username.length() < 5) {
38 | throw new BadCredentialsException("Username not found.");
39 | }
40 | if (password.length() < 5) {
41 | throw new BadCredentialsException("Wrong password.");
42 | }
43 |
44 | //Right now just authenticate on the basis of the user=pass
45 | if (username.equalsIgnoreCase(password)) {
46 | SessionUser u = new SessionUser();
47 | u.setUsername(username);
48 | u.setCreated(new Date());
49 | AuthenticationTokenImpl auth = new AuthenticationTokenImpl(u.getUsername(), Collections.emptyList());
50 | auth.setAuthenticated(true);
51 | auth.setDetails(u);
52 | service.setValue(String.format("%s:%s", u.getUsername().toLowerCase(), auth.getHash()), u, TimeUnit.SECONDS, 3600L, true);
53 | return auth;
54 | } else {
55 |
56 | }
57 | return null;
58 | }
59 |
60 | @Override
61 | public boolean supports(Class> type) {
62 | return type.equals(UsernamePasswordAuthenticationToken.class);
63 | }
64 |
65 | }
66 |
--------------------------------------------------------------------------------
/src/main/java/np/com/ngopal/spring/boot/redis/config/RedisConfig.java:
--------------------------------------------------------------------------------
1 | /*
2 | * To change this license header, choose License Headers in Project Properties.
3 | * To change this template file, choose Tools | Templates
4 | * and open the template in the editor.
5 | */
6 |
7 | package np.com.ngopal.spring.boot.redis.config;
8 |
9 | import org.springframework.beans.factory.annotation.Value;
10 | import org.springframework.context.annotation.Bean;
11 | import org.springframework.context.annotation.Configuration;
12 | import org.springframework.context.annotation.Primary;
13 | import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
14 | import org.springframework.data.redis.core.RedisTemplate;
15 | import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
16 | import org.springframework.data.redis.serializer.StringRedisSerializer;
17 |
18 | /**
19 | *
20 | * @author NGM
21 | */
22 | @Configuration
23 | public class RedisConfig {
24 |
25 | @Value("${redis.host}")
26 | private String redisHost;
27 |
28 | @Value("${redis.port}")
29 | private Integer redisPort;
30 |
31 | @Value("${redis.pass}")
32 | private String redisPass;
33 |
34 | @Bean
35 | @Primary
36 | JedisConnectionFactory jedisConnectionFactory() throws Exception {
37 | JedisConnectionFactory factory = new JedisConnectionFactory();
38 | factory.setHostName(redisHost);
39 | factory.setPort(redisPort);
40 | if (redisPass != null) {
41 | factory.setPassword(redisPass);
42 | }
43 | factory.setUsePool(true);
44 |
45 | return factory;
46 | }
47 |
48 | @Bean
49 | RedisTemplate< String, Object> redisTemplate() throws Exception {
50 | final RedisTemplate< String, Object> template = new RedisTemplate< String, Object>();
51 | template.setConnectionFactory(jedisConnectionFactory());
52 | template.setKeySerializer(new StringRedisSerializer());
53 |
54 | template.setHashValueSerializer(new Jackson2JsonRedisSerializer<>(Object.class));
55 | template.setValueSerializer(new Jackson2JsonRedisSerializer<>(Object.class));
56 | return template;
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/src/main/java/np/com/ngopal/spring/boot/redis/config/SecurityConfiguration.java:
--------------------------------------------------------------------------------
1 | /*
2 | * To change this license header, choose License Headers in Project Properties.
3 | * To change this template file, choose Tools | Templates
4 | * and open the template in the editor.
5 | */
6 | package np.com.ngopal.spring.boot.redis.config;
7 |
8 | import java.util.Arrays;
9 | import lombok.extern.slf4j.Slf4j;
10 | import np.com.ngopal.spring.boot.redis.jwt.JWTAuthenticationFilter;
11 | import np.com.ngopal.spring.boot.redis.jwt.JWTLoginFilter;
12 | import np.com.ngopal.spring.boot.redis.jwt.TokenAuthenticationService;
13 | import np.com.ngopal.spring.boot.redis.service.RedisService;
14 | import org.springframework.beans.factory.annotation.Autowired;
15 | import org.springframework.boot.autoconfigure.security.SecurityProperties;
16 | import org.springframework.boot.web.servlet.FilterRegistrationBean;
17 | import org.springframework.context.annotation.Bean;
18 | import org.springframework.context.annotation.Configuration;
19 | import org.springframework.core.annotation.Order;
20 | import org.springframework.security.authentication.AuthenticationManager;
21 | import org.springframework.security.authentication.ProviderManager;
22 | import org.springframework.security.config.annotation.web.builders.HttpSecurity;
23 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
24 | import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
25 | import org.springframework.web.cors.CorsConfiguration;
26 | import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
27 | import org.springframework.web.filter.CorsFilter;
28 |
29 | /**
30 | *
31 | * @author Narayan
32 | */
33 | @Slf4j
34 | @Configuration
35 | @Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
36 | public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
37 |
38 | @Autowired
39 | private TokenAuthenticationService tokenService;
40 |
41 | @Autowired
42 | private RedisService redisService;
43 |
44 | @Override
45 | protected AuthenticationManager authenticationManager() throws Exception {
46 | return new ProviderManager(Arrays.asList((AuthenticationProviderImpl) new AuthenticationProviderImpl(redisService)));
47 | }
48 |
49 | @Bean
50 | public FilterRegistrationBean corsFilter() {
51 | UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
52 | CorsConfiguration config = new CorsConfiguration();
53 | config.setAllowCredentials(true);
54 | config.addAllowedOrigin("*");
55 | config.addAllowedHeader("*");
56 | config.addAllowedMethod("*");
57 | source.registerCorsConfiguration("/**", config);
58 | FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
59 | bean.setOrder(0);
60 | return bean;
61 | }
62 |
63 | @Override
64 | protected void configure(HttpSecurity http) throws Exception {
65 |
66 | http.headers().cacheControl();
67 |
68 | http.csrf().disable()
69 | .authorizeRequests()
70 | .anyRequest().authenticated()
71 | .and()
72 | .httpBasic().disable()
73 | .addFilterBefore(new JWTLoginFilter("/login", authenticationManager(), tokenService), UsernamePasswordAuthenticationFilter.class)
74 | .addFilterBefore(new JWTAuthenticationFilter(tokenService), UsernamePasswordAuthenticationFilter.class);
75 |
76 | }
77 |
78 | }
79 |
--------------------------------------------------------------------------------
/src/main/java/np/com/ngopal/spring/boot/redis/domain/AuthenticationTokenImpl.java:
--------------------------------------------------------------------------------
1 | /*
2 | * To change this license header, choose License Headers in Project Properties.
3 | * To change this template file, choose Tools | Templates
4 | * and open the template in the editor.
5 | */
6 | package np.com.ngopal.spring.boot.redis.domain;
7 |
8 | import java.util.Collection;
9 | import lombok.Getter;
10 | import lombok.Setter;
11 | import lombok.ToString;
12 | import lombok.extern.slf4j.Slf4j;
13 | import org.springframework.security.authentication.AbstractAuthenticationToken;
14 | import org.springframework.security.core.GrantedAuthority;
15 | import org.springframework.util.DigestUtils;
16 |
17 | /**
18 | *
19 | * @author Narayan G. Maharjan <me@ngopal.com.np>
20 | */
21 | @Slf4j
22 | @ToString(callSuper = true)
23 | public class AuthenticationTokenImpl extends AbstractAuthenticationToken {
24 |
25 | @Setter
26 | private String username;
27 |
28 | public AuthenticationTokenImpl(String principal, Collection extends GrantedAuthority> authorities) {
29 | super(authorities);
30 | this.username = principal;
31 | }
32 |
33 | public void authenticate() {
34 | if (getDetails() != null && getDetails() instanceof SessionUser && !((SessionUser) getDetails()).hasExpired()) {
35 | setAuthenticated(true);
36 | } else {
37 | setAuthenticated(false);
38 | }
39 | }
40 |
41 | @Override
42 | public Object getCredentials() {
43 | return "";
44 | }
45 |
46 | @Override
47 | public Object getPrincipal() {
48 | return username != null ? username.toString() : "";
49 | }
50 |
51 | public String getHash() {
52 | return DigestUtils.md5DigestAsHex(String.format("%s_%d", username, ((SessionUser) getDetails()).getCreated().getTime()).getBytes());
53 | }
54 |
55 | }
56 |
--------------------------------------------------------------------------------
/src/main/java/np/com/ngopal/spring/boot/redis/domain/SessionUser.java:
--------------------------------------------------------------------------------
1 |
2 | package np.com.ngopal.spring.boot.redis.domain;
3 |
4 | import java.time.LocalDateTime;
5 | import java.time.ZoneId;
6 | import java.util.Date;
7 | import lombok.*;
8 |
9 | /*
10 | * To change this license header, choose License Headers in Project Properties.
11 | * To change this template file, choose Tools | Templates
12 | * and open the template in the editor.
13 | */
14 | /**
15 | *
16 | * @author NGM
17 | */
18 | @Data
19 | public class SessionUser {
20 |
21 | private String username;
22 |
23 | private String password;
24 |
25 | private Date created;
26 |
27 | public boolean hasExpired() {
28 | if(created == null){
29 | return true;
30 | }
31 | LocalDateTime localDateTime = created.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
32 | localDateTime = localDateTime.plusHours(1);
33 | return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant()).before(new Date());
34 | }
35 |
36 | }
37 |
--------------------------------------------------------------------------------
/src/main/java/np/com/ngopal/spring/boot/redis/jwt/JWTAuthenticationFilter.java:
--------------------------------------------------------------------------------
1 | /*
2 | * To change this license header, choose License Headers in Project Properties.
3 | * To change this template file, choose Tools | Templates
4 | * and open the template in the editor.
5 | */
6 | package np.com.ngopal.spring.boot.redis.jwt;
7 |
8 | import java.io.IOException;
9 | import javax.servlet.FilterChain;
10 | import javax.servlet.ServletException;
11 | import javax.servlet.ServletRequest;
12 | import javax.servlet.ServletResponse;
13 | import javax.servlet.http.HttpServletRequest;
14 | import org.springframework.security.core.Authentication;
15 | import org.springframework.security.core.context.SecurityContextHolder;
16 | import org.springframework.web.filter.GenericFilterBean;
17 |
18 | /**
19 | *
20 | * @author NGM
21 | */
22 | public class JWTAuthenticationFilter extends GenericFilterBean {
23 |
24 | private TokenAuthenticationService service;
25 |
26 | public JWTAuthenticationFilter(TokenAuthenticationService service) {
27 | this.service = service;
28 | }
29 |
30 | @Override
31 | public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
32 | Authentication authentication = service.getAuthentication((HttpServletRequest) request);
33 | SecurityContextHolder.getContext().setAuthentication(authentication);
34 | filterChain.doFilter(request, response);
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/main/java/np/com/ngopal/spring/boot/redis/jwt/JWTLoginFilter.java:
--------------------------------------------------------------------------------
1 | /*
2 | * To change this license header, choose License Headers in Project Properties.
3 | * To change this template file, choose Tools | Templates
4 | * and open the template in the editor.
5 | */
6 | package np.com.ngopal.spring.boot.redis.jwt;
7 |
8 | import com.fasterxml.jackson.databind.ObjectMapper;
9 | import java.io.IOException;
10 | import javax.servlet.FilterChain;
11 | import javax.servlet.ServletException;
12 | import javax.servlet.http.HttpServletRequest;
13 | import javax.servlet.http.HttpServletResponse;
14 | import np.com.ngopal.spring.boot.redis.domain.AuthenticationTokenImpl;
15 | import np.com.ngopal.spring.boot.redis.domain.SessionUser;
16 | import org.springframework.security.authentication.AuthenticationManager;
17 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
18 | import org.springframework.security.core.Authentication;
19 | import org.springframework.security.core.AuthenticationException;
20 | import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
21 | import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
22 |
23 | /**
24 | *
25 | * @author NGM
26 | */
27 | public class JWTLoginFilter extends AbstractAuthenticationProcessingFilter {
28 |
29 | private TokenAuthenticationService tokenAuthenticationService;
30 |
31 | public JWTLoginFilter(String url, AuthenticationManager authenticationManager, TokenAuthenticationService service) {
32 | super(new AntPathRequestMatcher(url));
33 | setAuthenticationManager(authenticationManager);
34 | tokenAuthenticationService = service;
35 | }
36 |
37 | @Override
38 | public Authentication attemptAuthentication(HttpServletRequest httpServletRequest, HttpServletResponse hsr1) throws AuthenticationException, IOException, ServletException {
39 | SessionUser credentials = new ObjectMapper().readValue(httpServletRequest.getInputStream(), SessionUser.class);
40 | UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(credentials.getUsername(), credentials.getPassword());
41 | return getAuthenticationManager().authenticate(token);
42 | }
43 |
44 | @Override
45 | protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authentication)
46 | throws IOException, ServletException {
47 |
48 | AuthenticationTokenImpl auth = (AuthenticationTokenImpl) authentication;
49 | tokenAuthenticationService.addAuthentication(response, auth);
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/src/main/java/np/com/ngopal/spring/boot/redis/jwt/TokenAuthenticationService.java:
--------------------------------------------------------------------------------
1 | /*
2 | * To change this license header, choose License Headers in Project Properties.
3 | * To change this template file, choose Tools | Templates
4 | * and open the template in the editor.
5 | */
6 | package np.com.ngopal.spring.boot.redis.jwt;
7 |
8 | import io.jsonwebtoken.Claims;
9 | import io.jsonwebtoken.ExpiredJwtException;
10 | import io.jsonwebtoken.Jwts;
11 | import io.jsonwebtoken.SignatureAlgorithm;
12 | import java.util.Collections;
13 | import java.util.Date;
14 | import java.util.HashMap;
15 | import java.util.Map;
16 | import javax.servlet.http.HttpServletRequest;
17 | import javax.servlet.http.HttpServletResponse;
18 | import np.com.ngopal.spring.boot.redis.domain.AuthenticationTokenImpl;
19 | import np.com.ngopal.spring.boot.redis.domain.SessionUser;
20 | import np.com.ngopal.spring.boot.redis.service.RedisService;
21 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
22 | import org.springframework.security.core.Authentication;
23 | import org.springframework.security.core.token.Sha512DigestUtils;
24 | import org.springframework.util.DigestUtils;
25 |
26 | /**
27 | *
28 | * @author NGM
29 | */
30 | public class TokenAuthenticationService {
31 |
32 | private RedisService service;
33 |
34 | private long EXPIRATIONTIME = 1000 * 60 * 60; // 1 hr
35 |
36 | private String secret;
37 |
38 | private String tokenPrefix = "Bearer";
39 |
40 | private String headerString = "Authorization";
41 |
42 |
43 |
44 | public TokenAuthenticationService(RedisService service, String key) {
45 | this.service = service;
46 | secret = Sha512DigestUtils.shaHex(key);
47 | }
48 |
49 | public void addAuthentication(HttpServletResponse response, AuthenticationTokenImpl auth) {
50 | // We generate a token now.
51 | Map claims = new HashMap<>();
52 | claims.put("username", auth.getPrincipal());
53 | claims.put("hash", auth.getHash());
54 | String JWT = Jwts.builder()
55 | .setSubject(auth.getPrincipal().toString())
56 | .setClaims(claims)
57 | .setExpiration(new Date(System.currentTimeMillis() + EXPIRATIONTIME))
58 | .signWith(SignatureAlgorithm.HS512, secret)
59 | .compact();
60 | response.addHeader(headerString, tokenPrefix + " " + JWT);
61 | }
62 |
63 | public Authentication getAuthentication(HttpServletRequest request) {
64 | String token = request.getHeader(headerString);
65 | if (token == null) {
66 | return null;
67 | }
68 | //remove "Bearer" text
69 | token = token.replace(tokenPrefix, "").trim();
70 |
71 | //Validating the token
72 | if (token != null && !token.isEmpty()) {
73 | // parsing the token.`
74 | Claims claims = null;
75 | try {
76 | claims = Jwts.parser()
77 | .setSigningKey(secret)
78 | .parseClaimsJws(token).getBody();
79 |
80 | } catch ( Exception e) {
81 | return null;
82 | }
83 |
84 | //Valid token and now checking to see if the token is actally expired or alive by quering in redis.
85 | if (claims != null && claims.containsKey("username")) {
86 | String username = claims.get("username").toString();
87 | String hash = claims.get("hash").toString();
88 | SessionUser user = (SessionUser) service.getValue(String.format("%s:%s", username,hash), SessionUser.class);
89 | if (user != null) {
90 | AuthenticationTokenImpl auth = new AuthenticationTokenImpl(user.getUsername(), Collections.emptyList());
91 | auth.setDetails(user);
92 | auth.authenticate();
93 | return auth;
94 | } else {
95 | return new UsernamePasswordAuthenticationToken(null, null);
96 | }
97 |
98 | }
99 | }
100 | return null;
101 | }
102 | }
103 |
--------------------------------------------------------------------------------
/src/main/java/np/com/ngopal/spring/boot/redis/resource/UserResource.java:
--------------------------------------------------------------------------------
1 | /*
2 | * To change this license header, choose License Headers in Project Properties.
3 | * To change this template file, choose Tools | Templates
4 | * and open the template in the editor.
5 | */
6 |
7 | package np.com.ngopal.spring.boot.redis.resource;
8 |
9 | import javax.servlet.http.HttpServletResponse;
10 | import np.com.ngopal.spring.boot.redis.domain.AuthenticationTokenImpl;
11 | import np.com.ngopal.spring.boot.redis.service.RedisService;
12 | import org.springframework.beans.factory.annotation.Autowired;
13 | import org.springframework.web.bind.annotation.RequestMapping;
14 | import org.springframework.web.bind.annotation.RequestMethod;
15 | import org.springframework.web.bind.annotation.RestController;
16 |
17 | /**
18 | *
19 | * @author NGM
20 | */
21 | @RestController
22 | @RequestMapping("/user")
23 | public class UserResource {
24 |
25 | @Autowired
26 | private RedisService service;
27 |
28 | @RequestMapping(method = RequestMethod.GET)
29 | public String getName(AuthenticationTokenImpl auth, HttpServletResponse response) {
30 | return auth.getPrincipal().toString();
31 | }
32 |
33 | @RequestMapping(value = "/processor", method = RequestMethod.GET)
34 | public Integer getProcessor(AuthenticationTokenImpl auth, HttpServletResponse response) {
35 | return Runtime.getRuntime().availableProcessors();
36 | }
37 |
38 | @RequestMapping(value = "/logout", method = RequestMethod.GET)
39 | public String logout(AuthenticationTokenImpl auth, HttpServletResponse response) {
40 | service.setValue(auth.getPrincipal().toString().toLowerCase(), "");
41 | return "Logout Successfully";
42 | }
43 |
44 | }
45 |
--------------------------------------------------------------------------------
/src/main/java/np/com/ngopal/spring/boot/redis/service/RedisService.java:
--------------------------------------------------------------------------------
1 | /*
2 | * To change this license header, choose License Headers in Project Properties.
3 | * To change this template file, choose Tools | Templates
4 | * and open the template in the editor.
5 | */
6 | package np.com.ngopal.spring.boot.redis.service;
7 |
8 | import com.fasterxml.jackson.databind.ObjectMapper;
9 | import java.util.ArrayList;
10 | import java.util.Iterator;
11 | import java.util.List;
12 | import java.util.Set;
13 | import java.util.concurrent.TimeUnit;
14 | import lombok.extern.slf4j.Slf4j;
15 | import org.springframework.beans.factory.annotation.Autowired;
16 | import org.springframework.core.Ordered;
17 | import org.springframework.core.annotation.Order;
18 | import org.springframework.data.redis.core.RedisTemplate;
19 | import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
20 | import org.springframework.data.redis.serializer.StringRedisSerializer;
21 | import org.springframework.stereotype.Service;
22 |
23 | /**
24 | *
25 | * @author Narayan
26 | */
27 | @Order(Ordered.HIGHEST_PRECEDENCE)
28 | @Service("redisService")
29 | @Slf4j
30 | public class RedisService {
31 |
32 | @Autowired
33 | private ObjectMapper mapper;
34 |
35 | @Autowired
36 | private RedisTemplate< String, Object> template;
37 |
38 | public synchronized List getKeys(final String pattern) {
39 | template.setHashValueSerializer(new StringRedisSerializer());
40 | template.setValueSerializer(new StringRedisSerializer());
41 | Set redisKeys = template.keys(pattern);
42 | // Store the keys in a List
43 | List keysList = new ArrayList<>();
44 | Iterator it = redisKeys.iterator();
45 | while (it.hasNext()) {
46 | String data = it.next();
47 | keysList.add(data);
48 | }
49 | return keysList;
50 | }
51 |
52 | public synchronized Object getValue(final String key) {
53 |
54 | template.setHashValueSerializer(new StringRedisSerializer());
55 | template.setValueSerializer(new StringRedisSerializer());
56 | return template.opsForValue().get(key);
57 | }
58 |
59 | public synchronized Object getValue(final String key, Class clazz) {
60 | template.setHashValueSerializer(new Jackson2JsonRedisSerializer<>(Object.class));
61 | template.setValueSerializer(new Jackson2JsonRedisSerializer<>(Object.class));
62 |
63 | Object obj = template.opsForValue().get(key);
64 | return mapper.convertValue(obj, clazz);
65 | }
66 |
67 | public void setValue(final String key, final Object value) {
68 | setValue(key, value, TimeUnit.HOURS, 5, false);
69 | }
70 |
71 | public void setValue(final String key, final Object value, boolean marshal) {
72 | if (marshal) {
73 | template.setHashValueSerializer(new Jackson2JsonRedisSerializer<>(Object.class));
74 | template.setValueSerializer(new Jackson2JsonRedisSerializer<>(Object.class));
75 | } else {
76 | template.setHashValueSerializer(new StringRedisSerializer());
77 | template.setValueSerializer(new StringRedisSerializer());
78 | }
79 | template.opsForValue().set(key, value);
80 | // set a expire for a message
81 | template.expire(key, 5, TimeUnit.MINUTES);
82 | }
83 |
84 | public void setValue(final String key, final Object value, TimeUnit unit, long timeout) {
85 | setValue(key, value, unit, timeout, false);
86 | }
87 |
88 | public void setValue(final String key, final Object value, TimeUnit unit, long timeout, boolean marshal) {
89 | if (marshal) {
90 | template.setHashValueSerializer(new Jackson2JsonRedisSerializer<>(Object.class));
91 | template.setValueSerializer(new Jackson2JsonRedisSerializer<>(Object.class));
92 | } else {
93 | template.setHashValueSerializer(new StringRedisSerializer());
94 | template.setValueSerializer(new StringRedisSerializer());
95 | }
96 | template.opsForValue().set(key, value);
97 | // set a expire for a message
98 | template.expire(key, timeout, unit);
99 | }
100 |
101 | }
102 |
--------------------------------------------------------------------------------
/src/main/resources/application.properties:
--------------------------------------------------------------------------------
1 | # To change this license header, choose License Headers in Project Properties.
2 | # To change this template file, choose Tools | Templates
3 | # and open the template in the editor.
4 |
5 | # show sql statements issued by JPA
6 | #spring.jpa.show-sql=true
7 |
8 | # enable debug logging for spring boot and hibernate classes
9 | # this is equivalent to passing '--debug' as command line argument
10 | #logging.level.org.springframework.boot=DEBUG
11 | #logging.level.org.hibernate.SQL=DEBUG
12 |
13 | # log to file (absolute/relative path of log file)
14 | #logging.file=path/to/log/file.log
15 |
16 | redis.host = localhost
17 | redis.port = 6379
18 | redis.pass =
19 | ENC_KEY=dkdi38393kd
--------------------------------------------------------------------------------
/src/main/resources/rebel.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------