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");
    }
}

到此就可以测试了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot整合Spring Security主要是为了提供安全控制功能,帮助开发者快速地在Spring Boot应用中添加身份验证、授权和会话管理等安全性措施。以下是基本步骤: 1. 添加依赖:首先,在Maven或Gradle项目中添加Spring Security的相关依赖到pom.xml或build.gradle文件中。 ```xml <!-- Maven --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <!-- Gradle --> implementation 'org.springframework.boot:spring-boot-starter-security' ``` 2. 配置WebSecurityConfigurerAdapter:在`src/main/resources/application.properties`或application.yml中配置一些基础属性,如启用HTTPS、密码加密策略等。然后创建一个实现了`WebSecurityConfigurerAdapter`的类,进行具体的配置,如设置登录页面、认证器、过滤器等。 ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/css/**", "/js/**", "/images/**").permitAll() // 允许静态资源访问 .anyRequest().authenticated() // 所有其他请求需要认证 .and() .formLogin() // 设置基于表单的身份验证 .loginPage("/login") // 登录页URL .defaultSuccessUrl("/") // 登录成功后的默认跳转URL .usernameParameter("username") .passwordParameter("password") .and() .logout() // 注销功能 .logoutUrl("/logout") .logoutSuccessUrl("/") .deleteCookies("JSESSIONID"); } // ... 其他配置如自定义用户DetailsService、密码编码器等 } ``` 3. 用户服务(UserDetailsService):如果需要从数据库或其他数据源获取用户信息,需要实现`UserDetailsService`接口并提供用户查询逻辑。 4. 运行应用:启动Spring Boot应用后,Spring Security将自动处理HTTP请求的安全检查,例如身份验证和授权。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值