【微服务|Spring Security③】基于Session的认证方式|实现认证功能

2.3 实现认证功能

2.3.1 认证页面

在webapp/WEB-INF/views下定义认证页面login.jsp,页面实 现可填入用户名 密码,触发登录将提交表单信息至/login ,内容如下:

<%--
  Created by IntelliJ IDEA.
  User: uncle
  Date: 2021/7/22
  Time: 下午9:43
  To change this template use File | Settings | File Templates.
--%>
<%@ 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页面:

package com.uncle.security.springmvc.config;

import com.uncle.security.springmvc.interceptor.SimpleAuthenticationInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

/**
 * @program: security-springmvc
 * @description:
 * @author: 步尔斯特
 * @create: 2021-07-22 21:34
 */
@Configuration//就相当于springmvc.xml文件
@EnableWebMvc
@ComponentScan(basePackages = "com.uncle.security.springmvc"
        ,includeFilters = {
    
    @ComponentScan.Filter(type = FilterType.ANNOTATION,value = Controller.class)})
public class WebConfig implements WebMvcConfigurer {
    
    

    @Autowired
    SimpleAuthenticationInterceptor simpleAuthenticationInterceptor;

    //视频解析器
    @Bean
    public InternalResourceViewResolver viewResolver(){
    
    
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/view/");
        viewResolver.setSuffix(".jsp");
        return viewResolver;
    }

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


启动项目,访问/路径地址,进行测试

启动

在这里插入图片描述
点击控制台生成的地址

在这里插入图片描述

2.3.2 认证接口

用户进入认证页面,输入账号和密码,点击登录,请求/login进行身份认证。

定义认证接口,此接口用于对传来的用户名、密码校验,若成功则返回该用户的详细信息,否则抛出错误异常:

package com.uncle.security.springmvc.service;

import com.uncle.security.springmvc.model.AuthenticationRequest;
import com.uncle.security.springmvc.model.UserDto;

/**
 * @program: security-springmvc
 * @description:
 * @author: 步尔斯特
 * @create: 2021-07-22 23:22
 */
public interface AuthenticationService {
    
    
    /**
     * 用户认证
     * @param authenticationRequest 用户认证请求,账号和密码
     * @return 认证成功的用户信息
     */
    UserDto authentication(AuthenticationRequest authenticationRequest);
}

认证请求结构:

package com.uncle.security.springmvc.model;

import lombok.Data;

/**
 * @program: security-springmvc
 * @description:
 * @author: 步尔斯特
 * @create: 2021-07-22 23:25
 */
@Data
public class AuthenticationRequest {
    
    
    //认证请求参数,账号、密码。
    /**
     * 用户名
     */
    private String username;

    /**
     * 密码
     */
    private String password;

}

认证成功后返回的用户详细信息,也就是当前登录用户的信息:

package com.uncle.security.springmvc.model;

import lombok.AllArgsConstructor;
import lombok.Data;

import java.util.Set;

/**
 * @program: security-springmvc
 * @description:
 * @author: 步尔斯特
 * @create: 2021-07-22 23:25
 */
@Data
@AllArgsConstructor
public class UserDto {
    
    
    //用户身份信息
    private String id;
    private String username;
    private String password;
    private String fullname;
    private String mobile;
}

认证实现类,根据用户名查找用户信息,并校验密码,这里模拟了两个用户:

package com.uncle.security.springmvc.service;

import com.uncle.security.springmvc.model.AuthenticationRequest;
import com.uncle.security.springmvc.model.UserDto;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @program: security-springmvc
 * @description:
 * @author: 步尔斯特
 * @create: 2021-07-22 23:27
 */
@Service
public class AuthenticationServiceImpl implements  AuthenticationService{
    
    
    /**
     * 用户认证,校验用户身份信息是否合法
     *
     * @param authenticationRequest 用户认证请求,账号和密码
     * @return 认证成功的用户信息
     */
    @Override
    public UserDto authentication(AuthenticationRequest authenticationRequest) {
    
    
        //校验参数是否为空
        if(authenticationRequest == null
                || StringUtils.isEmpty(authenticationRequest.getUsername())
                || StringUtils.isEmpty(authenticationRequest.getPassword())){
    
    
            throw new RuntimeException("账号和密码为空");
        }
        //根据账号去查询数据库,这里测试程序采用模拟方法
        UserDto user = getUserDto(authenticationRequest.getUsername());
        //判断用户是否为空
        if(user == null){
    
    
            throw new RuntimeException("查询不到该用户");
        }
        //校验密码
        if(!authenticationRequest.getPassword().equals(user.getPassword())){
    
    
            throw new RuntimeException("账号或密码错误");
        }
        //认证通过,返回用户身份信息
        return user;
    }
    //根据账号查询用户信息
    private 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"));
    }
}

登录Controller,对/login请求处理,它调用AuthenticationService完成认证并返回登录结果提示信息:

package com.uncle.security.springmvc.controller;

import com.uncle.security.springmvc.model.AuthenticationRequest;
import com.uncle.security.springmvc.model.UserDto;
import com.uncle.security.springmvc.service.AuthenticationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

/**
 * @program: security-springmvc
 * @description:
 * @author: 步尔斯特
 * @create: 2021-07-22 23:33
 */
@RestController
public class LoginController {
    
    

    @Autowired
    AuthenticationService authenticationService;

    @RequestMapping(value = "/login",produces = "text/plain;charset=utf-8")
    public String login(AuthenticationRequest authenticationRequest, HttpSession session){
    
    
    
        UserDto userDto = authenticationService.authentication(authenticationRequest);
        return userDto.getUsername() +"登录成功";
    }
}

启动项目,访问/路径地址,进行测试

启动 在这里插入图片描述
点击控制台生成的地址 在这里插入图片描述

填入错误的用户信息,页面返回错误信息: 在这里插入图片描述

填入正确的用户信息,页面提示登录成功: 在这里插入图片描述

以上的测试全部符合预期,到目前为止最基础的认证功能已经完成,它仅仅实现了对用户身份凭证的校验,若某用户认证成功,只能说明他是该系统的一个合法用户,仅此而已。

猜你喜欢

转载自blog.csdn.net/CSDN_SAVIOR/article/details/125682738