springboot整合springsecurity例子和踩过的坑

第一,创建项目1. 导入依赖

  <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</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.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity5</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!--以下是对Mybatis的整合和数据库的连接-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.9</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.18</version>
        </dependency>

2.配置application文件的配置

#下面是对网络的以下配置
server.port=8081
server.port.http=8080
server.error.path=/error
server.servlet.session.timeout=30m
server.tomcat.uri-encoding=utf-8
server.tomcat.threads.max=500
server.tomcat.basedir=/home/sang/tmp
#以下是对秘钥的配置
server.ssl.key-store-type=JKS
server.ssl.key-store=sang.p12
server.ssl.key-alias=tomcathttps
server.ssl.key-store-password=123456
server.ssl.enabled=true
#下面是对Thymeleaf的缓存关闭的情况,还有就是对其的一些配置
spring.thymeleaf.cache=false
spring.mvc.view.prefix=classpath:/templates/
spring.mvc.view.suffix=.html
另外还有就是mysql的要在yaml里面写的
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/security?userSSL=false&serverTimezone=UTC
    type: com.alibaba.druid.pool.DruidDataSource
    username: root
    password: 111

3. 导入对应的sang.p12文件

4. 导入静态资源

//静态资源1
css
images
fonts
js
layui
//静态资源2
welcome1.html
member-add.html
login_page.html
index.html

5.配置https和http的转换java类

package cn.mldn.secutity.config;


import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Configuration
public class HttpsConfig {

    @Bean
    public ServletWebServerFactory servletContainer() {
        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
            @Override
            protected void postProcessContext(Context context) {
                SecurityConstraint constraint = new SecurityConstraint();
                constraint.setUserConstraint("CONFIDENTIAL");
                SecurityCollection collection = new SecurityCollection();
                collection.addPattern("/*");
                constraint.addCollection(collection);
                context.addConstraint(constraint);
            }
        };
        tomcat.addAdditionalTomcatConnectors(createHTTPConnector());
        return tomcat;
    }

    private Connector createHTTPConnector() {
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");

        connector.setScheme("http");
        connector.setSecure(false);
//		http 端口
        connector.setPort(8080);
        //https端口 配置成application中的servlet.port的端口
        connector.setRedirectPort(8081);
        return connector;
    }

}

6.创建DAO和Service层

@Mapper
@Repository
public interface security_mybatisMapper {
    security_mybatis getsecurity_mybatisMapperByName(String name);
    String  getRoleByName(String name);
}

<?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="cn.mldn.secutity.mapper.security_mybatisMapper">
    <select id="getsecurity_mybatisMapperByName" parameterType="String" resultType="cn.mldn.secutity.bean.security_mybatis">
        select *  from security.security_mybatis where name=#{name}
    </select>
    <select id="getRoleByName" parameterType="String" resultType="String">
        select role from security.security_mybatis where name=#{name}
    </select>
</mapper>
package cn.mldn.secutity.service;

import cn.mldn.secutity.bean.security_mybatis;
import cn.mldn.secutity.mapper.security_mybatisMapper;
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 security_mybatisService implements UserDetailsService {
    @Autowired
    security_mybatisMapper security_mybatisMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        security_mybatis user = security_mybatisMapper.getsecurity_mybatisMapperByName(username);
        if (user == null) {
            throw new UsernameNotFoundException("账户不存在");
        }
        user.setRole(security_mybatisMapper.getRoleByName(username));
        return user;
    }

    public String getRoleByName(String username) {
        String roleByName = security_mybatisMapper.getRoleByName(username);
        return roleByName;
    }
}

7.配置具体的config

package cn.mldn.secutity.config;

import cn.mldn.secutity.service.security_mybatisService;
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.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;


@Configuration
@EnableWebSecurity
public class MyWebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    security_mybatisService mybatisService;
    @Bean
    PasswordEncoder passwordEncoder() {
    //此次没有加密练习
        return NoOpPasswordEncoder.getInstance();
    }


    //这个方法就就是配置数据的一个方法的,比如从数据库拿数据出来就是这个方法
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        /*auth.inMemoryAuthentication()
                .withUser("admin").password("123").roles("USER")
                .and()
                .withUser("zheng").password("123").roles("ADMIN");*/
        auth.userDetailsService(mybatisService);
        }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
    	//这部分是作为练习的		
        /*http.authorizeRequests()
                .antMatchers("/user/**")
                .hasRole("ADMIN")
                .antMatchers("/hello/**")
                .access("hasAnyRole('AMDIN','USER')")
                .antMatchers("/db/**")
                .access("hasRole('ADMIN') and hasRole('USER')")
                .anyRequest()
                .authenticated()
                .and()
                .formLogin()
                .loginPage("/login1")
                .permitAll()
                .loginProcessingUrl("/login")
                .usernameParameter("username")
                .passwordParameter("password")
                .successHandler(new AuthenticationSuccessHandler() {
                    @Override
                    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {

                    }
                })
                .failureHandler(new AuthenticationFailureHandler() {
                    @Override
                    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {

                    }
                })
                .permitAll()
                .and()
                .csrf()
                .disable();*/
                //这部分是对真正实现的练习
        http.authorizeRequests()
                .antMatchers("/user/city")
                .hasRole("admin")
                .antMatchers("/hello/**")
                .access("hasAnyRole('hello')")
                .antMatchers("/db/**")
                .access("hasRole('admin') and hasRole('hello')")
                .mvcMatchers("/css/**","/fonts/**","/images/**","/js/**","/layui/**","/hello/**","/user/**")
                .permitAll()
                .and()
                .authorizeRequests()
                .antMatchers("/login_page")
                .permitAll()
                .anyRequest()
                .authenticated()
                .and()
                .csrf()
                .disable();
        http.formLogin()
                .loginPage("/login_page")
                .loginProcessingUrl("/index")
                .usernameParameter("username")
                .passwordParameter("password");
    }
}

到此就可以测试了


版权声明:本文为weixin_46635575原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。