Spring Boot login with Redis Admin user membership

Source: Internet
Author: User
Tags uuid docker run

Usage Scenarios

Many restful API interfaces now have a sign-in design, which is to request a token-based interface through a login request before initiating a formal request. After the application is successful, all subsequent payment requests are taken with this token, and the server verifies the validity of the request through this token. This token usually has an expiration date, typically a few hours.

In the public platform interface, for example, the key interface should be preceded with access token. Access_token is the public number's globally unique ticket, valid for 7,200 seconds, and repeated fetches will result in the Access_token failure of the last acquisition.

Installation configuration for Redis (Docker)
 docker pull redis docker run --name redis -d -p 6379:6379 redis:latest
Springboot Project 1. When creating a new project, select Redis Dependent 2. Configure Redis parameters in Application.yml (use yml here)
spring:  redis:    host: 192.168.147.129    port: 6379
3.REDIS constant Entity class
package com.example.demo.bean;/** * Created by Administrator on 2017/12/11 0011. */public interface RedisConstant {    String TOKEN_PREFIX = "token_%s";    //2小时    Integer EXPIRE = 60;}
4. Configure the Interceptor for login

Configuration class

package com.example.demo.config;import com.example.demo.util.MyInterceptor;import org.springframework.context.annotation.Configuration;import org.springframework.web.servlet.config.annotation.InterceptorRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;/** * Demo class * * @author aslan * @date 2017/12/12 */@Configurationpublic class LoginInterceptor extends WebMvcConfigurerAdapter{    @Override    public void addInterceptors(InterceptorRegistry registry) {        registry.addInterceptor(new MyInterceptor()).addPathPatterns("/test/**");    }}

Implementation class:

Package Com.example.demo.util;import Org.springframework.context.applicationcontext;import Org.springframework.data.redis.core.stringredistemplate;import Com.example.demo.bean.redisconstant;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.jca.context.springcontextresourceadapter;import Org.springframework.util.stringutils;import Org.springframework.web.context.support.webapplicationcontextutils;import Org.springframework.web.servlet.handlerinterceptor;import Org.springframework.web.servlet.modelandview;import Javax.servlet.servletcontext;import Javax.servlet.http.cookie;import javax.servlet.http.HttpServletRequest; Import javax.servlet.http.httpservletresponse;/** * Demo class * * @author Aslan * @date 2017/12/12 */public class Myinter Ceptor Implements handlerinterceptor{@Override public boolean prehandle (HttpServletRequest httpservletrequest, Http Servletresponse httpservletresponse, Object o) throws Exception {System.out.println ("pRe hander ");        Determine if the user is logged in, if not logged in, jump to login interface//Get token cookie[] cookies = httpservletrequest.getcookies ();        String token =null; for (Cookie cookie:cookies) {if ("token". Equals (Cookie.getname ())) {token = Cookie.getvalue ()                ;            Break        }}//redistemplate ServletContext context = Httpservletrequest.getservletcontext ();        ApplicationContext CTX = webapplicationcontextutils.getwebapplicationcontext (context);        Stringredistemplate redistemplate = Ctx.getbean (Stringredistemplate.class); Check whether the TOKEN exists from Redis with String tokenvalue = Redistemplate.opsforvalue (). Get (String.Format (redisconstant.token_prefix        , token));            if (Stringutils.isempty (Tokenvalue)) {System.out.println ("token" is not found in Redis "login Check");        return false;            }else {System.out.println ("Get token" + tokenvalue);        return true; }} @Override Public void Posthandle (HttpServletRequest httpservletrequest, HttpServletResponse httpservletresponse, Object o,    Modelandview Modelandview) throws Exception {System.out.println ("post hander"); } @Override public void Aftercompletion (HttpServletRequest httpservletrequest, HttpServletResponse httpservletrespon    SE, Object o, Exception e) throws Exception {System.out.println ("after"); }}
5. Login Controller
Package Com.example.demo.controller;import Com.example.demo.bean.redisconstant;import Com.sun.deploy.net.httprequest;import Com.sun.deploy.net.httpresponse;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.util.stringutils;import Org.springframework.web.bind.annotation.*;import Javax.servlet.http.cookie;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Java.util.UUID;import Java.util.concurrent.timeunit;import org.springframework.data.redis.core.stringredistemplate;/** * Created by Administrator on 2017/12/11 0011. */@RestController @requestmapping ("/login") public class Logincontroller {@Autowired private stringredistemplate Redi    stemplate;    @RequestMapping ("/") public String Index () {return "aha";  } @RequestMapping (value = "/loginbypost", method = requestmethod.post) public String loginbypost (@RequestParam (value                       = "Name", required = True) String name,       @RequestParam (value = "pwd", required = True) String pwd, httpservletresponse response        {//Generate token String token = Uuid.randomuuid (). toString ();        Set token to cookie inside cookie cookie = new Cookie ("token", token);        Cookie.setpath ("/");        Cookie.setmaxage (7200);        Response.addcookie (cookie);    return null; } @RequestMapping (value = "/loginbyget", method = requestmethod.get) public String loginbyget (@RequestParam (value = "Name", Required = True) string name, @RequestParam (value = "pwd", Required = True) string pwd , httpservletresponse response) {//Generate token String token = Uuid.randomuuid (). ToS        Tring ();        Integer expire = Redisconstant.expire; Redistemplate.opsforvalue (). Set (String.Format (Redisconstant.token_prefix, TOKEN), "Didididi", expire,        Timeunit.seconds); Set token to cookie inside cookie cookie = new Cookie ("Token ", token);        Cookie.setpath ("/");        Cookie.setmaxage (120);        Response.addcookie (cookie);    Return "Login Success";        } @RequestMapping (value = "/getit", method = requestmethod.get) public String getit (HttpServletRequest request) {        cookie[] cookies = request.getcookies ();        String token =null; for (Cookie cookie:cookies) {if ("token". Equals (Cookie.getname ())) {token = Cookie.getvalue ()                ;            Break        }} String Tokenvalue = Redistemplate.opsforvalue (). Get (String.Format (Redisconstant.token_prefix, TOKEN));        if (Stringutils.isempty (Tokenvalue)) {System.out.println ("token" is not found in Redis "login Check");        }else {System.out.println ("Get token" + token);    } return null; }}
6. Test controller
package com.example.demo.controller;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;/** * Demo class * * @author aslan * @date 2017/12/12 */@RestController@RequestMapping("/test")public class TestController {    @RequestMapping("/getone")    public String getone(){        return "in 3 getone";    }    @RequestMapping("/gettwo")    public String gettwo(){        return "in 3 gettwo";    }    @RequestMapping("/getthree")    public String getthree(){        return "in 3 getthree";    }}
7. Test method

Nginx Doing load Balancing

Spring Boot login with Redis Admin user membership

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.