IDEA Springboot mybatis springSecurity实现认证授权

新建springboot项目就不在多赘述了,首先,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.pan</groupId>
   <artifactId>demo</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <packaging>jar</packaging>

   <name>demo</name>
   <description>Demo project for Spring Boot</description>

   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>2.0.4.RELEASE</version>
      <relativePath/> <!-- lookup parent from repository -->
   </parent>

   <properties>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
      <java.version>1.8</java.version>
   </properties>

   <dependencies>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-jdbc</artifactId>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-thymeleaf</artifactId>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-web</artifactId>
      </dependency>
      <dependency>
         <groupId>org.mybatis.spring.boot</groupId>
         <artifactId>mybatis-spring-boot-starter</artifactId>
         <version>1.3.2</version>
      </dependency>

      <dependency>
         <groupId>mysql</groupId>
         <artifactId>mysql-connector-java</artifactId>
         <scope>runtime</scope>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-test</artifactId>
         <scope>test</scope>
      </dependency>

      <!-- JSON 相关包 START -->
      <dependency>
         <groupId>com.alibaba</groupId>
         <artifactId>fastjson</artifactId>
         <version>1.2.17</version>
      </dependency>
      <dependency>
         <groupId>com.fasterxml.jackson.core</groupId>
         <artifactId>jackson-core</artifactId>
      </dependency>

      <dependency>
         <groupId>com.google.code.gson</groupId>
         <artifactId>gson</artifactId>
      </dependency>
      <!-- JSON 相关包 END-->

      <!-- SpringSecurity依赖  START-->
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-security</artifactId>
      </dependency>
      <!-- SpringSecurity依赖 END-->

      <!-- thymeleaf -->
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-thymeleaf</artifactId>
      </dependency>
      <dependency>
         <groupId>org.thymeleaf.extras</groupId>
         <artifactId>thymeleaf-extras-springsecurity4</artifactId>
      </dependency>
      <!--end-->

      <!-- mybatis的分页插件 -->
      <dependency>
          <groupId>com.github.pagehelper</groupId>
          <artifactId>pagehelper</artifactId>
      </dependency>

      <!--springboot热部署插件 1.3版本之后才有-->
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-devtools</artifactId>
         <optional>true</optional>
      </dependency>

   </dependencies>

   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>

         <!-- myBatis auto generate -->
         <plugin>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-maven-plugin</artifactId>
            <version>1.3.5</version>
            <configuration>
               <verbose>true</verbose>
               <overwrite>true</overwrite>
            </configuration>
         </plugin>
      </plugins>
   </build>


</project>

至于热部署,前面博客有讲。。。

其次,application.properties

# 数据库连接信息
spring.datasource.url = jdbc:mysql://*******
spring.datasource.username =****
spring.datasource.password = *****
spring.datasource.driverClassName = com.mysql.jdbc.Driver

# 禁止默认springboot图标
spring.mvc.favicon.enabled=false
# thymeleaf相关配置参数
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.servlet.content-type=text/html
# 调试阶段关闭缓存,以适用热更新
spring.thymeleaf.cache=false
#mapper映射文件
mybatis.mapper-locations=classpath:mapper/**/*.xml

   然后就是使用mybatis生成entity  dao 以及mapper了

要注意的是entit要实现UserDetails,并实现方法,如下

package com.pan.demo.entity;

import com.pan.demo.constants.Constants;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.beans.Transient;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class User implements UserDetails{
    private Integer id;

    private String name;

    private String password;

    private String phone;

    private List<Function> functions;

    public List<Function> getFunctions() {
        return functions;
    }

    public void setFunctions(List<Function> functions) {
        this.functions = functions;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name == null ? null : name.trim();
    }

    /**
     * 获取当前用户所具有的菜单权限modid列表
     */
    private List<GrantedAuthority> getFuncAuthorities(List<Function> functions) {
        List<GrantedAuthority> auths = new ArrayList<>();
        if(this.name.equals(Constants.ADMIN_USERCODE)){
            auths.add( new SimpleGrantedAuthority("ROLE_ADMIN") );
        }
        if(functions !=null && !functions.isEmpty()){
            for (Function function : functions) {
                auths.add(new SimpleGrantedAuthority("ROLE_" + function.getModid().trim()));
                if(function.getSubFunctions() != null && !function.getSubFunctions().isEmpty()) auths.addAll(getFuncAuthorities(function.getSubFunctions()));
            }
        }
        return auths;
    }

    /** SpringSecurity User */
    private List<GrantedAuthority> auths;
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if(functions == null) return null;
        if(auths == null){
            auths = getFuncAuthorities(functions);
        }
        return auths;
    }

    @Transient
    public boolean isValidCredentials(String credentials) {
        return credentials != null && new BCryptPasswordEncoder().matches(credentials,getPassword());
    }


    public String getPassword() {
        return password;
    }

    @Override
    public String getUsername() {
        return name;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }

    public void setPassword(String password) {
        this.password = password == null ? null : password.trim();
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone == null ? null : phone.trim();
    }
}

然后就是我们的config文件WebSecurityConfig

package com.pan.demo.config;

import com.pan.demo.service.UserService;
import com.pan.demo.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
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.crypto.bcrypt.BCryptPasswordEncoder;

import javax.annotation.Resource;

@Configuration //必须加这个注解,用于生成一个配置类,
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true) //启用Security注解
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    LoginAuthenticationProvider authenticationProvider;

    @Resource
    UserServiceImpl userService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/drugcode/**","/invalidSession","/sendPhoneVerCode","/captcha/**").permitAll()
                .anyRequest()
                .authenticated()
                .and()
                .formLogin()
                .loginPage("/login")
                .usernameParameter("name")        //采用用户名登录  括号内与from表单name名一致
                .passwordParameter("password")    //修正密码框名称  括号内与from表单name名一致
                //.failureUrl("/login?error")     //登陆失败返回URL:/login?error
                .defaultSuccessUrl("/index")      //登陆成功跳转URL
                .permitAll()                       //登陆页面全部权限可访问
                .and()
                .logout()                    //注销
                .permitAll()
                .and()
                .sessionManagement()
                .maximumSessions(1)                //最大session并发数
                .maxSessionsPreventsLogin(false);  //是否保持当前用户登录
               /* .expiredSessionStrategy(new SessionExpiredStrategy());*/ //挤下线异常处理
        // 关闭csrf 防止循环定向
        http.csrf().disable();
        // session失效后跳转   //跳转方法,返回login
        http.sessionManagement().invalidSessionUrl("/invalidSession");
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(authenticationProvider);
        auth.userDetailsService(userService).passwordEncoder(new BCryptPasswordEncoder());
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        /* 错误页面 */
        web.ignoring().antMatchers("/error/**");
        /* 静态资源路径 */
        web.ignoring().antMatchers("/static/**");
        web.ignoring().antMatchers("/images/**");
        web.ignoring().antMatchers("/css/**");
        web.ignoring().antMatchers("/js/**");
        /* 网页图标 */
        web.ignoring().antMatchers("/favicon.ico");
        /* druid监控 */
       /* web.ignoring().antMatchers("/druid/**");*/
    }
}

以及登录获取权限类LoginAuthenticationProvider

package com.pan.demo.config;

import com.pan.demo.constants.Results;
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.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.Collection;

@Component
public class LoginAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    UserDetailsService userDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String principal = authentication.getPrincipal().toString();
        String password = (String) authentication.getCredentials();
        //检查用户名有效性
        UserDetails userDetails = userDetailsService.loadUserByUsername(principal);
        // 获取用户权限集合
        Collection<? extends GrantedAuthority> authorities = userDetails.getAuthorities();
        if(password.equals(userDetails.getPassword())){
            return new UsernamePasswordAuthenticationToken(userDetails, userDetails.getPassword(), authorities);
        }else {
            throw new BadCredentialsException(Results.USER_PASSWORD_WRONG.getMsg());
        }
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }
}

至于测试的话,spring Security 有提供登录页面,只是一般都习惯用自己的,上面的可能只是我做为代码搬运工的一些简单理解,各取所需就好,还未完善。。。 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值