IntelliJ IDEA + gradle + springboot + security + mybatis + oracle + Thymeleaf 项目构建简单的登录验证
- 1. 新建一个项目
- 2. 项目基本配置
- 2.1 配置 application.properties
- 2.2 新建一个实体类 UserEntity.java
- 2.3 新建 UserMapper.xml
- 2.4 新建 UserMapper.java
- 2.5 新建 UserService.java(实际没有用到)
- 2.6 新建 LoginController.java
- 2.7 新建 login.html
- 2.8 新建 LoginUserDetails.java 并继承 User
- 2.9 新建 LoginUserDetailsService.java 并实现 UserDetailsService 接口
- 2.10 新建 UserPasswordEncoder.java 并实现 PasswordEncoder 接口
- 2.11 新建 LoginAuthenticationProvider.java 并实现 AuthenticationProvider 接口
- 2.12 新建 SecurityConfig.java 继承 WebSecurityConfigurerAdapter
- 附1 项目结构截图
- 附2 数据库截图
- 附3 登录成功失败的截图
- 附4 build.gradle
1. 新建一个项目
1.2 file —> new —> Module
1.2 选择 Spring Initializr,其他保持默认
1.3 Type 选择 Gradle Project (第三项)
1.Maven Project (Generate a Maven based project archive)
2.Maven POM (Generate a Maven pom.xml)
3.Gradle Project (Generate a Gradle based project archive)
4.Gradle Config (Generate a Gradle build file)
2和4只创建对应的配置文件(pom.xml / gradle.build),而1和3在创建配置文件之外还会创建Spring Boot项目中的一些常规文件(SpringBootApplication 类和对应的代码结构)
1.4 选择需要的 Dependencies —>Next —>Finish
目录结构:
2. 项目基本配置
2.1 配置 application.properties
#oracle 配置
spring.datasource.url=jdbc:oracle:thin:@192.168.1.100:1521/ORCL
spring.datasource.username=TEST
spring.datasource.password=111111
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
#jpa 配置
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jackson.serialization.indent_output=true
#mybatis 配置
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.configuration.map-underscore-to-camel-case=true
mybatis.type-aliases-package=com.example.d3.mapper
mybatis.type-handlers-package=org.apache.ibatis.type.LocalDateTypeHandler
2.2 新建一个实体类 UserEntity.java
package com.example.d3.entity;
import javax.persistence.*;
@Entity
@Table(name = "testUser")
public class UserEntity {
/**
* @Id 标注用于声明一个实体类的属性映射为数据库的主键列。该属性通常置于属性声明语句之前,
* 可与声明语句同行,也可写在单独行上。
* @Id 标注也可置于属性的getter方法之前。
*/
@Id
/**
* @GeneratedValue 用于标注主键的生成策略,通过strategy 属性指定。默认情况下,
* JPA 自动选择一个最适合底层数据库的主键生成策略:SqlServer对应identity,
* MySQL 对应 auto increment。
* 在javax.persistence.GenerationType中定义了以下几种可供选择的策略:
* –IDENTITY:采用数据库ID自增长的方式来自增主键字段,Oracle 不支持这种方式;
* –AUTO: JPA自动选择合适的策略,是默认选项;
* –SEQUENCE:通过序列产生主键,通过@SequenceGenerator 注解指定序列名,
* MySql不支持这种方式
* –TABLE:通过表产生主键,框架借由表模拟序列产生主键,使用该策略可以使应用更易于数据库移植。
*/
@GeneratedValue
@Column(name = "id")
private Integer id;
@Column(name = "name", columnDefinition = "varchar2(20) not null")
private String name;
@Column(name = "pass")
private String pass;
@Column(name = "auth", columnDefinition = "varchar(10) default 'USER'")
private String auth;
//getter、setter ... (可以用lombok实现)
}
2.3 新建 UserMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.example.d3.mapper.UserMapper">
<select id="getUserByName" resultType="com.example.d3.entity.UserEntity">
SELECT *
FROM
TEST_USER
WHERE
NAME = #{name}
</select>
</mapper>
2.4 新建 UserMapper.java
package com.example.d3.mapper;
import com.example.d3.entity.UserEntity;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface UserMapper {
UserEntity getUserByName(String name);
}
2.5 新建 UserService.java(实际没有用到)
package com.example.d3.service;
import com.example.d3.entity.UserEntity;
import com.example.d3.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Autowired
UserMapper userMapper;
public UserEntity getUserByName(String name){
return userMapper.getUserByName(name);
}
}
2.6 新建 LoginController.java
package com.example.d3.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class LoginController {
private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
@RequestMapping("login")
public String showLogin(){
logger.info("1");
return "login";
}
}
2.7 新建 login.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<title>Spring Security Example </title>
</head>
<body>
<form th:action="@{/login}" method="post">
<div><label> User Name : <input type="text" name="name"/> </label></div>
<div><label> Password: <input type="password" name="pass"/> </label></div>
<div><input type="submit" value="Sign In"/></div>
</form>
</body>
</html>
2.8 新建 LoginUserDetails.java 并继承 User
package com.example.d3;
//import org.apache.catalina.User;
import com.example.d3.entity.UserEntity;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
public class LoginUserDetails extends User {
public LoginUserDetails(UserEntity user) {
super(user.getName(), user.getPass(), AuthorityUtils.createAuthorityList(user.getAuth()));
}
}
2.9 新建 LoginUserDetailsService.java 并实现 UserDetailsService 接口
package com.example.d3;
//import com.example.d3.entity.User;
import com.example.d3.entity.UserEntity;
import com.example.d3.mapper.UserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
/**
* 登录专用类
*/
@Service
public class LoginUserDetailsService implements UserDetailsService {
private static final Logger logger = LoggerFactory.getLogger(LoginUserDetailsService.class);
@Autowired
UserMapper userMapper;
/**
* 登录验证时,通过 username 获取用户信息
* 并返回给 UserDetails 放到 spring 的全局缓存 SecurityContextHolder 中,供授权器使用
*
* @param username
* @return
* @throws UsernameNotFoundException
*/
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
logger.info(username);
if (username == null || "".equals(username)){
throw new UsernameNotFoundException("用户名为空");
}
UserEntity user = userMapper.getUserByName(username);
if (user == null){
throw new UsernameNotFoundException("用户不存在");
}
return new LoginUserDetails(user);
}
}
2.10 新建 UserPasswordEncoder.java 并实现 PasswordEncoder 接口
package com.example.d3;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
/**
* 自定义密码加密方法
*/
@Component
public class UserPasswordEncoder implements PasswordEncoder {
private static final Logger logger = LoggerFactory.getLogger(UserPasswordEncoder.class);
/**
* 把参数按照特定的解析规则进行解析。
*
* @param rawPassword
* @return
*/
@Override
public String encode(CharSequence rawPassword) {
return rawPassword.toString();
}
/**
* 验证从存储中获取的编码密码与编码后提交的原始密码是否匹配。如果密码匹配,则返回 true;
* 如果不匹配,则返回 false。第一个参数表示需要被解析的密码。第二个参数表示存储的密码。
*
* @param rawPassword
* @param encodedPassword
* @return
*/
@Override
public boolean matches(CharSequence rawPassword, String encodedPassword) {
logger.info("rawPassword = " + rawPassword);
logger.info("encodedPassword = " + encodedPassword);
logger.info(String.valueOf(encode(rawPassword).equals(encodedPassword)));
return encode(rawPassword).equals(encodedPassword);
}
/**
* 如果解析的密码能够再次进行解析且达到更安全的结果则返回 true,否则返回 false。
* 默认返回 false
*
* @param encodedPassword
* @return
*/
@Override
public boolean upgradeEncoding(String encodedPassword) {
return false;
}
}
2.11 新建 LoginAuthenticationProvider.java 并实现 AuthenticationProvider 接口
package com.example.d3;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
@Component
public class LoginAuthenticationProvider implements AuthenticationProvider {
@Autowired
private LoginUserDetailsService loginUserDetailsService;
@Autowired
private PasswordEncoder passwordEncoder;
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
//获取输入的用户名
String username = authentication.getName();
//获取输入的明文
String rawPassword = (String) authentication.getCredentials();
//查询用户是否存在
UserDetails user = loginUserDetailsService.loadUserByUsername(username);
//验证密码
if (!passwordEncoder.matches(rawPassword, user.getUsername())) {
throw new BadCredentialsException("输入密码错误!");
}
return new UsernamePasswordAuthenticationToken(user, rawPassword, user.getAuthorities());
}
@Override
public boolean supports(Class<?> authentication) {
return authentication.equals(UsernamePasswordAuthenticationToken.class);
}
}
2.12 新建 SecurityConfig.java 继承 WebSecurityConfigurerAdapter
package com.example.d3;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import java.io.PrintWriter;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
LoginAuthenticationProvider loginAuthenticationProvider;
@Bean
UserDetailsService loginUserService() { // 注册UserDetailsService 的bean
return new LoginUserDetailsService();
}
@Autowired
UserPasswordEncoder userPasswordEncoder;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests() //开启登录配置
.antMatchers("/hello").hasRole("admin") //表示/hello 这个接口, 要有 admin 这个角色
.anyRequest().authenticated() //其它接口,登录之后就能访问
.and()
.formLogin()
.loginPage("/login") //定义登录页面,未登录时,访问一个需要登录之后才能登录的接口,会自动跳转到该页面
.loginProcessingUrl("/login") //登录处理的接口
.usernameParameter("name") //定义登录时,用户名的 key,默认为 username
.passwordParameter("pass") //定义登录时,密码的 key,默认为 password
// .successHandler(new AuthenticationSuccessHandler() { //登录成功后的处理 可以用 lambda 代替 匿名内部类
.successHandler((request, response, authentication) -> {
response.setContentType("application/json;charset=utf-8");
PrintWriter printWriter = response.getWriter();
printWriter.write("Login success");
printWriter.flush();
})
// .failureHandler(new AuthenticationFailureHandler() { //登录失败后的处理 可以用 lambda 代替 匿名内部类
.failureHandler((request, response, exception) -> {
response.setContentType("application/json;charset=utf-8");
PrintWriter printWriter = response.getWriter();
printWriter.write(exception.getMessage());
printWriter.flush();
})
.permitAll() //和表单相关的接口直接通过
.and()
.logout()
.logoutUrl("/logout")
// .logoutSuccessHandler(new LogoutSuccessHandler() {可以用 lambda 代替 匿名内部类
.logoutSuccessHandler((request, response, authentication) -> {
response.setContentType("application/json;charset=utf-8");
PrintWriter printWriter = response.getWriter();
printWriter.write("logout success");
printWriter.flush();
})
.permitAll();
http.cors().disable(); // 开启跨域访问
http.csrf().disable(); //开启模拟请求,比如 API POST 测试工具,不开启时 API POST 报403错误
}
//设置某个地址不需要拦截
@Override
public void configure(WebSecurity web) throws Exception {
//对于在header里面增加token等类似情况,放行所有OPTION
web.ignoring().antMatchers(HttpMethod.OPTIONS, "/**");S请求。
web.ignoring().antMatchers("/css/**", "/js/**", "/picture/**");
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(loginAuthenticationProvider);
}
}
附1 项目结构截图
附2 数据库截图
附3 登录成功失败的截图
附4 build.gradle
plugins {
id 'org.springframework.boot' version '2.2.2.RELEASE'
id 'io.spring.dependency-management' version '1.0.8.RELEASE'
id 'java'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
configurations {
developmentOnly
runtimeClasspath {
extendsFrom developmentOnly
}
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:2.1.1'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
runtimeOnly 'com.oracle.ojdbc:ojdbc8'
compile group: 'com.oracle.ojdbc', name: 'orai18n', version: '19.3.0.0'
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
testCompile group: 'junit', name: 'junit', version: '4.13'
testImplementation 'org.springframework.security:spring-security-test'
}
test {
useJUnitPlatform()
}