spring security

2019-10-14  本文已影响0人  十二找十三
  1. pom
        <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.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity4</artifactId>
            <version>3.0.2.RELEASE</version>
        </dependency>

2.核心配置

package com.ccbckj.config;

import com.ccbckj.service.MyUserDetailsService;
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.method.configuration.EnableGlobalMethodSecurity;
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.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.csrf.CsrfFilter;
import org.springframework.web.filter.CharacterEncodingFilter;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)//开启security的注解模式
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    @Autowired
    private MyUserDetailsService myUserDetailsService;

    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable();

        http
                //使用form表单post方式进行登录
                .formLogin()
                //登录页面为自定义的登录页面
                .loginPage("/login")
                //设置登录成功跳转页面,error=true控制页面错误信息的展示
                .successForwardUrl("/index").failureUrl("/login?error=true")
                .permitAll()
                .and()
                //允许不登陆就可以访问的方法,多个用逗号分隔
                .authorizeRequests().antMatchers("/test").permitAll()
                //其他的需要授权后访问
                .anyRequest().authenticated();


        //session管理,失效后跳转
        http.sessionManagement().invalidSessionUrl("/login");

        //单用户登录,如果有一个登录了,同一个用户在其他地方登录将前一个剔除下线
        //http.sessionManagement().maximumSessions(1).expiredSessionStrategy(expiredSessionStrategy());
        //单用户登录,如果有一个登录了,同一个用户在其他地方不能登录   
        http.sessionManagement().maximumSessions(1).maxSessionsPreventsLogin(true);// .and().invalidSessionUrl("/login"); //session失效跳转路径

        //退出时删除cookies
        http.logout().deleteCookies("JESSIONID");

        //解决中文乱码问题
        CharacterEncodingFilter filter = new CharacterEncodingFilter();
        filter.setEncoding("UTF-8"); filter.setForceEncoding(true);
        http.addFilterBefore(filter, CsrfFilter.class);
    }

    // 配置用户验证
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(myUserDetailsService).passwordEncoder(new BCryptPasswordEncoder());

        // 测试时 不用连接数据库查询
        // auth.inMemoryAuthentication().withUser("user").password(new BCryptPasswordEncoder().encode("user")).roles("USER");
    }


    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

3.测试类

@RestController
public class IndexController {

    @RequestMapping("/index")
    public ModelAndView index(){
        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();

        System.out.println("====>" + userDetails.getUsername());// 获取当前请求的用户名
        return new ModelAndView("/index");
    }

    @RequestMapping("/test")
    public Object test(){
        return "test";
    }


    @RequestMapping("/aaa")
    public Object aaa(){
        return "aaa";
    }

    /**
     * 自定义登录页面
     * @param error 错误信息显示标识
     * @return
     *
     */
    @GetMapping("/login")
    public ModelAndView login(String error){
        System.out.println("login====>");
        ModelAndView modelAndView = new ModelAndView("/login");
        modelAndView.addObject("error", error);
        return modelAndView;
    }
}
  1. 关于session问题
server:
  servlet:
    session:
      timeout: 61   # 不得少于一分钟  少于一分钟按照一分钟算   springboot的版本是2.1.7.RELEASE
上一篇下一篇

猜你喜欢

热点阅读