spring-boot登陸過濾功能

supportlss發表於2019-01-19

先簡單說一下我們工程的架構:前端工程是採用react,後端工程採用spring-cloud,裡面分為zuul工程和其他功能模組。zuul工程除了提供後端的路由轉發,還可以做全域性的過濾器,所以我選擇在這個工程裡面寫登陸校驗功能。

session配置

這裡使用redis儲存session資訊。
下載依賴,在pom.xml裡面加入

<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>

配置session儲存,在application.yml裡面加入

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

session超時,在application.yml裡面配置timeout貌似沒有效果,我們在啟動類裡面加入超時配置註解

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

新增redis類配置,新建一個redisConfig類,然後寫入

package com.config;

import org.springframework.context.annotation.Configuration;

@Configuration
public class RedisConfig {

    public RedisConfig() {

    }

}

過濾器

這裡使用zuulFilter,實現了每個http請求都經過這個過濾器,然後通過session中是否存在使用者名稱,判斷session是否超時。如果超時就返回錯誤提示,前端再根據超時的http請求碼進行跳轉。

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);
        //queryString.indexOf("tag=process") > -1)是為了外系統呼叫這個系統跳過登陸約定傳過來的值
        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;
        }
    }
}

這裡還需要在啟動類中注入這個類

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

登陸的程式碼

主要就是把前端傳來的使用者名稱密碼放到session中,並進行校驗。如果校驗成功,返回登陸成功,否則,返回登陸失敗。前端再根據登陸情況做路由跳轉。

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);
    }

}

最後,貼一下啟動類的程式碼

@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);
    }
}

相關文章