基於session的傳統認證授權詳解


基於session的傳統認證授權詳解


概念部分

1.認證

用戶認證是判斷一個用戶的身份是否合法的過程,用戶去訪問系統資源時系統要求驗證用戶的身份信 息,身份合法方可繼續訪問,不合法則拒絕訪問。常見的用戶身份認證方式有:用戶名密碼登錄,二維碼登錄,手 機短信登錄,指紋認證等方式。

2.會話

用戶認證通過后,為了避免用戶的每次操作都進行認證可將用戶的信息保證在會話中。會話就是系統為了保持當前 用戶的登錄狀態所提供的機制,常見的有基於session方式、基於token方式等。

基於session的認證方式如下圖:

它的交互流程是,用戶認證成功后,在服務端生成用戶相關的數據保存在session(當前會話)中,發給客戶端的
sesssion_id 存放到 cookie 中,這樣用戶客戶端請求時帶上 session_id 就可以驗證服務器端是否存在 session 數
據,以此完成用戶的合法校驗,當用戶退出系統或session過期銷毀時,客戶端的session_id也就無效了。

3.授權

拿微信舉例,用戶擁有發紅包功能的權限才可以正常使用發送紅包功能,擁有發朋友圈功能的權限才可以使用發朋友 圈功能,這個根據用戶的權限來控制用戶使用資源的過程就是授權。

授權是用戶認證通過根據用戶的權限來控制用戶訪問資源的過程,擁有資源的訪問權限則正常訪問,沒有 權限則拒絕訪問。

項目代碼部分

創建工程

以idea為例file->new project->maven->next->填寫groupid和artifactid->項目名和項目位置->finish

導入依賴

設置maven(省略)

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.chen.security</groupId>
    <artifactId>security</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.1.5.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.0.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.8</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>security-springmvc</finalName>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <configuration>
                        <source>1.8</source>
                        <target>1.8</target>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.apache.tomcat.maven</groupId>
                    <artifactId>tomcat7-maven-plugin</artifactId>
                    <version>2.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-resources-plugin</artifactId>
                    <configuration>
                        <encoding>utf-8</encoding>
                        <useDefaultDelimiters>true</useDefaultDelimiters>
                        <resources>
                            <resource>
                                <directory>src/main/resources</directory>
                                <filtering>true</filtering>
                                <includes>
                                    <include>**/*</include>
                                </includes>
                            </resource>
                            <resource>
                                <directory>src/main/java</directory>
                                <includes>
                                    <include>**/*.xml</include>
                                </includes>
                            </resource>
                        </resources>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</project>

目錄結構

Spring 容器配置

在config包下定義ApplicationConfig.java,它對應web.xml中ContextLoaderListener的配置

@Configuration
@ComponentScan(basePackages = "com.chen.security",
        excludeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION,value = Controller.class)})
public class ApplicationConfig {
}

servletContext配置

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.chen.security"
,includeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION,value =
Controller.class)})
public class WebConfig implements WebMvcConfigurer {
//視頻解析器
@Bean
public InternalResourceViewResolver viewResolver(){
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB‐INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}

加載 Spring容器

在init包下定義Spring容器初始化類SpringApplicationInitializer,此類實現WebApplicationInitializer接口, Spring容器啟動時加載WebApplicationInitializer接口的所有實現類。

public class SpringApplicationInitializer extends
AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[] { ApplicationConfig.class };//指定rootContext的配置類
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] { WebConfig.class }; //指定servletContext的配置類
}
@Override
protected String[] getServletMappings() {
return new String [] {"/"};
}
}

實現認證功能

認證頁面

在webapp/WEB-INF/views下定義認證頁面login.jsp,本案例只是測試認證流程,頁面沒有添加css樣式,頁面實 現可填入用戶名,密碼,觸發登錄將提交表單信息至/login,內容如下:

<%@ page contentType="text/html;charset=UTF‐8" pageEncoding="utf‐8" %>
<html>
<head>
<title>用戶登錄</title>
</head>
<body>
<form action="login" method="post">
用戶名:<input type="text" name="username"><br>
密&nbsp;&nbsp;&nbsp;碼:
<input type="password" name="password"><br>
<input type="submit" value="登錄">
</form>
</body>
</html>

在WebConfig中新增如下配置,將/直接導向login.jsp頁面:

@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("login");
}

配置如下運行

運行訪問

定義認證接口以及相關實體類(文件具體位置見目錄結構)

AuthenticationService.java

/**
* 認證服務
*/
public interface AuthenticationService {
/**
* 用戶認證
* @param authenticationRequest 用戶認證請求
* @return 認證成功的用戶信息
*/
UserDto authentication(AuthenticationRequest authenticationRequest);
}

AuthenticationRequest.java

@Data
public class AuthenticationRequest {
/**
* 用戶名
*/
private String username;
/**
* 密碼
*/
private String password;
}

UserDto.java

/**
* 當前登錄用戶信息
*/
@Data
@AllArgsConstructor
public class UserDto {
private String id;
private String username;
private String password;
private String fullname;
private String mobile;
}

實現這個接口

AuthenticationServiceimpl.java

@Service
public class AuthenticationServiceImpl implements AuthenticationService{
@Override
public UserDto authentication(AuthenticationRequest authenticationRequest) {
if(authenticationRequest == null
|| StringUtils.isEmpty(authenticationRequest.getUsername())
|| StringUtils.isEmpty(authenticationRequest.getPassword())){
throw new RuntimeException("賬號或密碼為空");
}
UserDto userDto = getUserDto(authenticationRequest.getUsername());
if(userDto == null){
throw new RuntimeException("查詢不到該用戶");
}
if(!authenticationRequest.getPassword().equals(userDto.getPassword())){
throw new RuntimeException("賬號或密碼錯誤");
}
return userDto;
}
//模擬用戶查詢
public UserDto getUserDto(String username){
return userMap.get(username);
}
//用戶信息
private Map<String,UserDto> userMap = new HashMap<>();
{
userMap.put("zhangsan",new UserDto("1010","zhangsan","123","張三","133443"));
userMap.put("lisi",new UserDto("1011","lisi","456","李四","144553"));
}
}

LoginController.java

@RestController
public class LoginController {
@Autowired
private AuthenticationService authenticationService;
/**
* 用戶登錄
* @param authenticationRequest 登錄請求
* @return
*/
@PostMapping(value = "/login",produces = {"text/plain;charset=UTF‐8"})
public String login(AuthenticationRequest authenticationRequest){
UserDetails userDetails = authenticationService.authentication(authenticationRequest);
return userDetails.getFullname() + " 登錄成功";
}
}

測試

登錄設定的賬號密碼登錄可以成功,否則登陸失敗

實現會話功能

在UserDto.java中新增一個常量作為Session的key

public static final String SESSION_USER_KEY = "_user";

修改LoginController

/**
* 用戶登錄
* @param authenticationRequest 登錄請求
* @param session http會話
* @return
*/
@PostMapping(value = "/login",produces = "text/plain;charset=utf‐8")
public String login(AuthenticationRequest authenticationRequest, HttpSession session){
UserDto userDto = authenticationService.authentication(authenticationRequest);
//用戶信息存入session
session.setAttribute(UserDto.SESSION_USER_KEY,userDto);
return userDto.getUsername() + "登錄成功";
}
@GetMapping(value = "logout",produces = "text/plain;charset=utf‐8")
public String logout(HttpSession session){
session.invalidate();
return "退出成功";
}

增加測試資源LoginController

/**
* 測試資源1
* @param session
* @return
*/
@GetMapping(value = "/r/r1",produces = {"text/plain;charset=UTF‐8"})
public String r1(HttpSession session){
String fullname = null;
Object userObj = session.getAttribute(UserDto.SESSION_USER_KEY);
if(userObj != null){
fullname = ((UserDto)userObj).getFullname();
}else{
fullname = "匿名";
}
return fullname + " 訪問資源1";
}
測試

未登錄情況下訪問/r/r1顯示 匿名訪問資源1

登錄情況下訪問則顯示 登錄者的全名 訪問資源1

實現授權功能

修改UserDto如下

@Data
@AllArgsConstructor
public class UserDto {
public static final String SESSION_USER_KEY = "_user";
private String id;
private String username;
private String password;
private String fullname;
private String mobile;
/**
* 用戶權限
*/
private Set<String> authorities;
}

並在AuthenticationServiceImpl中為模擬用戶初始化權限,其中張三給了p1權限,李四給了p2權限

//用戶信息
private Map<String,UserDto> userMap = new HashMap<>();
{
Set<String> authorities1 = new HashSet<>();
authorities1.add("p1");
Set<String> authorities2 = new HashSet<>();
authorities2.add("p2");
userMap.put("zhangsan",new UserDto("1010","zhangsan","123","張
三","133443",authorities1));
userMap.put("lisi",new UserDto("1011","lisi","456","李四","144553",authorities2));
}
private UserDetails getUserDetails(String username) {
return userDetailsMap.get(username);
}

我們想實現針對不同的用戶能訪問不同的資源,前提是得有多個資源,因此在LoginController中增加測試資源2

/**
* 測試資源2
* @param session
* @return
*/
@GetMapping(value = "/r/r2",produces = {"text/plain;charset=UTF‐8"})
public String r2(HttpSession session){
String fullname = null;
Object userObj = session.getAttribute(UserDto.SESSION_USER_KEY);
if(userObj != null){
fullname = ((UserDto)userObj).getFullname();
}else{
fullname = "匿名";
}
return fullname + " 訪問資源2";
}

增加攔截器

在interceptor包下定義SimpleAuthenticationInterceptor攔截器,實現授權攔截: 1、校驗用戶是否登錄 2、校驗用戶是否擁有操作權限

@Component
public class SimpleAuthenticationInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //在這個方法中校驗用戶請求的url是否在用戶的權限范圍內
        //取出用戶身份信息
        Object object = request.getSession().getAttribute(UserDto.SESSION_USER_KEY);
        if(object==null){
            //沒有認證提示登錄
            writeContent(response,"請登錄");
        }

        UserDto userDto=(UserDto) object;
        //獲取用戶權限
        //獲取請求的uri
        String requestURI = request.getRequestURI();
        if(userDto.getAuthorities().contains("p1")&&requestURI.contains("r/r1")){
            return true;
        }
        if(userDto.getAuthorities().contains("p2")&&requestURI.contains("r/r2")){
            return true;
        }

        writeContent(response,"沒有權限拒絕訪問");
        return false;
    }
    //響應信息給客戶端
    private void writeContent(HttpServletResponse response, String msg) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.println(msg);
        writer.close();
    }
}

在WebConfig中配置攔截器,匹配/r/**的資源為受保護的系統資源,訪問該資源的請求進入 SimpleAuthenticationInterceptor攔截器。

@Autowired
private SimpleAuthenticationInterceptor simpleAuthenticationInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(simpleAuthenticationInterceptor).addPathPatterns("/r/**");
}

測試

未登錄情況下,/r/r1與/r/r2均提示 “請先登錄”。 張三登錄情況下,由於張三有p1權限,因此可以訪問/r/r1,張三沒有p2權限,訪問/r/r2時提示 “權限不足 “。 李四登錄情況下,由於李四有p2權限,因此可以訪問/r/r2,李四沒有p1權限,訪問/r/r1時提示 “權限不足 “。 測試結果全部符合預期結果。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM