Home  >  Article  >  Java  >  Implementation code of spring-boot's login filtering function

Implementation code of spring-boot's login filtering function

不言
不言forward
2018-12-21 10:45:102952browse

The content of this article is about the spring-boot login filtering function. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Let’s briefly talk about the architecture of our project: the front-end project uses react, and the back-end project uses spring-cloud, which is divided into zuul project and other functional modules. In addition to providing back-end routing and forwarding, the zuul project can also do global filters, so I chose to write the login verification function in this project.

session configuration

Redis is used here to store session information.
Download dependencies, add

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.session</groupId>
    <artifactId>spring-session-data-redis</artifactId>
</dependency>

to pom.xml to configure session storage, add

session:
    store-type: redis
    timeout: 30
redis:
    database: 0
    host: 
    password: 
    port: 6379
    timeout: 300000

session timeout to application.yml, configuring timeout in application.yml seems to have no effect. We add the timeout configuration annotation in the startup class

@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 7200, redisFlushMode = RedisFlushMode.IMMEDIATE)

Add the redis class configuration, create a new redisConfig class, and then write

package com.config;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RedisConfig {
    public RedisConfig() {

    }
}

Filter

Using zuulFilter here, it is implemented Each http request goes through this filter, and then whether the session has timed out is determined by whether the user name exists in the session. If it times out, an error message will be returned, and the front end will jump based on the timed out http request code.

package com.config;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.ztesoft.cloud.Service.StaffService;
import com.ztesoft.cloud.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import javax.servlet.http.HttpServletRequest;
public class WebSecurityFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";//前置过滤器
    }
    @Override
    public int filterOrder() {
        return 0;//优先级为0,数字越大,优先级越低
    }
    @Override
    public boolean shouldFilter() {
        return true;//是否执行该过滤器,此处为true,说明需要过滤
    }
    @Autowired
    private StaffService staffService;
    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String queryString = request.getQueryString();
        Object username = request.getSession().getAttribute("username");
        Object password = request.getSession().getAttribute("password");
        User user = new User();
        if(username != null) {
            user.setUsername(username.toString());
        }
        if(password != null) {
            user.setPassword(password.toString());
        }
        Boolean verifyResult = this.staffService.verifyLoginUser(user);
        if ((queryString != null && queryString.indexOf("tag=process") > -1) || verifyResult) {
            ctx.setSendZuulResponse(true);// 对该请求进行路由
            ctx.setResponseStatusCode(200);
            ctx.set("isSuccess", true);// 设值,可以在多个过滤器时使用
            return null;
        } else {
            ctx.setSendZuulResponse(false);// 过滤该请求,不对其进行路由
            ctx.setResponseStatusCode(401);// 返回错误码,应该是401
            ctx.setResponseBody("session is out of time");// 返回错误内容
            ctx.set("isSuccess", false);
            return null;
        }
    }
}

Here you also need to inject this class into the startup class

    @Bean
    public WebSecurityFilter accessFilter() {
        return new WebSecurityFilter();
    }

Login code

The main thing is to put the username and password passed from the front end into the session, and perform check. If the verification is successful, login success will be returned; otherwise, login failure will be returned. The front end then makes routing jumps based on the login status.

package com.controller;

@RestController
@RequestMapping(value = "/system")
public class SystemController extends JdkSerializationRedisSerializer implements Serializable {

    @Autowired
    private StaffService staffService;

    @PostMapping("login")
    public ResponseEntity<String> login(@RequestBody User user, HttpSession session) {
        session.setAttribute("username", user.getUsername());
        session.setAttribute("password", user.getPassword());
        Boolean ret = this.staffService.verifyLoginUser(user);
        if(ret == true) {
            return new ResponseEntity<>("登陆成功", HttpStatus.OK);
        }
        return new ResponseEntity<>("登陆失败", HttpStatus.NON_AUTHORITATIVE_INFORMATION);
    }

}

Finally, post the code of the startup class

@SpringBootApplication
@EnableDiscoveryClient
@EnableZuulProxy
@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 7200, redisFlushMode = RedisFlushMode.IMMEDIATE)
@ComponentScan(excludeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = RibbonConfig.class))
@RibbonClients(defaultConfiguration = RibbonConfig.class)
public class PlatformWebApplication {
    @Bean
    public WebSecurityFilter accessFilter() {
        return new WebSecurityFilter();
    }
    public static void main(String[] args) {
        SpringApplication.run(PlatformWebApplication.class, args);
    }
}


The above is the detailed content of Implementation code of spring-boot's login filtering function. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete