随记:springboot+spring-security

该文章为备忘,个人用

package com.szq.le.config;

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

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@SpringBootApplication(scanBasePackages = { "com.szq.le.controller", "com.szq.le.service.impl", "com.szq.le.springcomponent" })
@ServletComponentScan
@MapperScan("com.szq.le.dao")
public class AppConfig extends SpringBootServletInitializer implements WebMvcConfigurer {

    @Bean
    protected WebSecurityConfigurerAdapter getWebSecurityConfigurerAdapter() {
        return new WebSecurityConfigurerAdapter() {

            @Override
            protected void configure(HttpSecurity http) throws Exception {
                http.csrf().disable().cors().and().formLogin();
                http.authorizeRequests().antMatchers("/api/fulladm/**").access("hasAnyRole({'admin','user'}) and isFullyAuthenticated()");
                http.authorizeRequests().antMatchers("/api/adm/**").access("hasAnyRole({'admin','user','abc'}) and isFullyAuthenticated()");
                http.authorizeRequests().antMatchers("/api/fullauth/**").fullyAuthenticated();
                http.authorizeRequests().antMatchers("/api/auth/**").authenticated();
                http.authorizeRequests().antMatchers("/**").permitAll();
                //重要,这里是CAS认证的配置入口
                http.exceptionHandling().authenticationEntryPoint(null);
            }
        };
    }

    @Bean
    protected BCryptPasswordEncoder getBCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    protected UserDetailsService getUserDetailsService(BCryptPasswordEncoder getBCryptPasswordEncoder) {
        return new UserDetailsService() {

            @Override
            public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
                return new UserDetails() {

                    private static final long serialVersionUID = 1L;

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

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

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

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

                    @Override
                    public String getUsername() {
                        return "admin";
                    }

                    @Override
                    public String getPassword() {
                        String s = getBCryptPasswordEncoder.encode("passw0rd");
                        System.out.println(s);
                        return s;
                    }

                    @Override
                    public Collection<? extends GrantedAuthority> getAuthorities() {
                        List<GrantedAuthority> list = new ArrayList<>();
                        list.add(new GrantedAuthority() {

                            private static final long serialVersionUID = 1L;

                            @Override
                            public String getAuthority() {
                                return "ROLE_abc";
                            }
                        });
                        return list;
                    }
                };
            }
        };
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedOrigins("*");
    }

}

有几个点需要注意:

  1. .formLogin()后面有各种方法,各种handler可以实现各种各样的扩展。自定义返回成功后的功能就在这里扩展。
  2. BCryptPasswordEncoder必须得配置一个,还有其他几个encoder可以用,一般情况下使用这个也就够了。
  3. UserDetailsService必须得配置一个,这里是最主要的扩展点,在这里可以自己实现各种各样的获取用户信息的功能,不管是从数据库还是从缓存获取。通过自定义这个bean,就不必使用spring-security自带的那个数据库获取用户信息的功能了。
  4. 如果是使用cas之类的认证,则**http.exceptionHandling().authenticationEntryPoint(null);**方法是配置认证入口的方法。

原创不易,转帖请注明出处 — ShiZhongqi

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值