6.基于Session的认证方式-实现认证功能

实现认证功能

认证页面

  • 在webapp/WEB-INF/views下定义认证页面login.isp,本案例只是测试认证流程,页面没有添加css样式,页面实现可填入户名,密码,触发登录将提交表单信息到/login ,内容如下:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    Title


    
用户名:
密码:
  • 在WebConfig中新增如下配置,将/直接导向login.jsp页面:
public void addViewControllers(ViewControllerRegistry registry){
    registry.addViewController("/").setViewName("login");
}
  • 启动项目,访问/路径地址,进行测试


    image

认证接口

  • 用户进入认证页面,输入账号和密码,点击登录,请求/login进行身份认证。
  • (1)定义认证接口,此接口用于对传来的用户名,密码校验,若成功则返回该用户的详细信息,否则抛出错误异常:
public interface AuthenticationService {
    /**
     * 用户请求
     * @param authenticationRequest 用户认证请求,账号和密码
     * @return 认证成功的用户信息
     */
    UserDto authentication(AuthenticationRequest authenticationRequest);
}
  • 认证请求结构:
/**
 * 认证请求参数,账号,密码
 */
public class AuthenticationRequest {
    private String username;
    private String password;
}
  • 认证成功后返回用户详细信息,也就是当前登录用户的信息:
/**
 * 用户身份信息
 */
@Data
public class UserDto {
    private String id;
    private String username;
    private String password;
    private String fullname;
    private String mobile;
}
  • 认证接口实现类:
@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 user = getUserDto(authenticationRequest.getUsername());
        if (user==null){
            throw new RuntimeException("查询不到该用户");
        }
        if (!authenticationRequest.getPassword().equals(user.getPassword())){
            throw new RuntimeException("账号或密码错误");
        }
        //认证通过返回用户身份信息
        return user;
    }

    /**
     * 根据账号查询用户信息
     * @param userName
     * @return
     */
    private UserDto getUserDto(String userName){
        return userDtoMap.get(userName);
    }

    /**
     * 用户信息
     */
    private Map userDtoMap=new HashMap<>();
    {
        userDtoMap.put("zs",new UserDto("1010","zs","123","张三","1224443"));
        userDtoMap.put("ls",new UserDto("1011","ls","123","李四","1224443"));
    }
}
  • Controller暴露接口
@RestController
public class LoginController {

    @Autowired
    AuthenticationService authenticationService;

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

你可能感兴趣的:(6.基于Session的认证方式-实现认证功能)