springboot集成springsecurity

https://www.cnblogs.com/ealenxie/p/9293768.html

https://blog.csdn.net/u013435893/article/details/79596628

https://blog.csdn.net/qq_35508033/article/details/79046441

http://www.cnblogs.com/softidea/p/7068149.html

https://blog.csdn.net/qq_38743954/article/details/84954197

框架:springboot+mybatis+mysql+html+jquery

1.pom添加dependency

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

2.继承WebSecurityConfigurerAdapter,重写protected void configure(HttpSecurity http) 和protected void configure(AuthenticationManagerBuilder auth) 方法;实现UserDetailsService 接口。或jdbc方式详见如下(2)

(1)

import org.apache.commons.codec.digest.Md5Crypt;
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.MessageDigestPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
@EnableWebSecurity
public class PitWebSecutiryConfig extends WebSecurityConfigurerAdapter{
    @Bean
    MyUserDetailsService myUserDetailsService(){
        return new MyUserDetailsService();
    }
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/js/**","/css/**").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
            .and()
            .logout().logoutUrl("/logout").logoutSuccessUrl("/login").invalidateHttpSession(true).deleteCookies("JSESSIONID")
            .and()
            .csrf().disable();
    }
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(myUserDetailsService()).passwordEncoder(new MessageDigestPasswordEncoder("MD5"));
    }
}

(2)

package pit.security;

import javax.annotation.Resource;
import javax.sql.DataSource;

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.MessageDigestPasswordEncoder;
@Configuration
@EnableWebSecurity
public class PitWebSecutiryConfig extends WebSecurityConfigurerAdapter{
    @Bean
    MyUserDetailsService myUserDetailsService(){
        return new MyUserDetailsService();
    }
    @Resource
    private DataSource dataSource;
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/js/**","/css/**").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
            .and()
            .logout().logoutUrl("/logout").logoutSuccessUrl("/login").invalidateHttpSession(true).deleteCookies("JSESSIONID")
            .and()
            .csrf().disable();
    }
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        auth.userDetailsService(myUserDetailsService()).passwordEncoder(new MessageDigestPasswordEncoder("MD5"));
        auth.jdbcAuthentication().dataSource(dataSource)
            .usersByUsernameQuery("SELECT username,LOWER(User_Password),true FROM UserTable where username= ?")
            .authoritiesByUsernameQuery("SELECT username,RESOURCE FROM T_USER_RESOURCES WHERE username= ?")
            .passwordEncoder(new MessageDigestPasswordEncoder("MD5"));
    }
}

3.登出,注意:2中的.csrf().disable()如果没有此语句,注销不成功,get 404 ,post 403.

<form action="/logout" method="get">
    <input type="submit" value="注销"/>
</form>

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
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.Component;

import pit.dao.UserTMapper;
import pit.model.UserT;
@Component
public class MyUserDetailsService implements UserDetailsService {
    @Autowired
    private UserTMapper utMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        //对应的权限添加
        authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
        UserT usert=utMapper.selectByComnum(username);
        User user=new User(username, usert.getUserPassword().toLowerCase(), authorities);
        return user;
    }

}
4.调用

@RequestMapping(value="/selectCompanyAll")
    public List<Pit_company> selectCompanyAll(){
        SecurityContext securityContext=SecurityContextHolder.getContext();
        System.out.println("=========="+securityContext.getAuthentication().toString());
        List<Pit_company> list=pitCompanyMapper.selectAll();
        return list;
    }

5.数据库连接池

package pit.config;

import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

@Configuration
public class DatasourceConfiguration {
    @Bean(name = "dataSource")
    @Qualifier(value = "dataSource")
    @Primary
    @ConfigurationProperties(prefix = "c3p0")
    public DataSource dataSource() {
        return DataSourceBuilder.create().type(com.mchange.v2.c3p0.ComboPooledDataSource.class).build();
    }
}

application.properties:

server.port=8080
#写法不起作用security.basic.enabled = false

c3p0.jdbcUrl=jdbc:mysql://ip:3306/数据库名称
c3p0.user=username
c3p0.password=password
c3p0.driverClass=com.mysql.jdbc.Driver
c3p0.minPoolSize=2
c3p0.maxPoolSize=10
c3p0.initialPoolSize=3
c3p0.maxIdleTime=30000

#---------------------------------------------------------
# c3p0反空闲设置,防止8小时失效问题28800
#---------------------------------------------------------
#idleConnectionTestPeriod要小于MySQL的wait_timeout
jdbc.c3p0.testConnectionOnCheckout=false
jdbc.c3p0.testConnectionOnCheckin=true
jdbc.c3p0.idleConnectionTestPeriod=3600

mybatis.mapperLocations=classpath:pit/mapper/*Mapper.xml   
mybatis.typeAliasesPackage=pit.dao

spring.servlet.multipart.max-file-size=100MB
spring.servlet.multipart.max-request-size=1000MB

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值