Spring Security的相关配置

下面的配置方法都是在继承WebSecurityConfigurerAdapter类情况下实现的:

在内存中配置用户名和密码
  • 继承WebSecurityConfigurerAdapter类,重写
    configure(AuthenticationManagerBuilder auth)
    方法
        auth.inMemoryAuthentication()
                .withUser("javaBoy")
                .password("123456")
                .roles("admin");
不拦截某些访问路径
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/js/**","/css/**","/image/**");
    }

拦截、登录相关配置(前后端未分离) ``````

下面的类都是重写configure(HttpSecurity http)实现的

  • and()方法,相当于关联2个配置
  • 下面的跳转页面,你都需要在teamplates下面拥有相关的页面才行,配置页面不是这里的重点
设置登录界面
  • 如果发现用户没有登录,就将他的访问请求修改为/login
  • 用户填完用户名和密码后,就可以请求/dologin登录
  • 可以将登录的userName修改为name
  • 可以将登录的password修改为pwd
  • 登录成功后,设置服务器端直接跳转到/success
  • 也可以设置将登录成功后,跳转到之前拦截的网址,如果没有拦截网站,则跳转到到/success
  • 登录失败界面/file
                .and()
                .formLogin()
                .loginPage("/login")            //设置未登录跳转路径为“/login”
                .loginProcessingUrl("/dologin") //登录访问接口
                .usernameParameter("name")
                .passwordParameter("pwd")
//                .successForwardUrl("/success") //服务端跳转  登录成功后,跳转到success页面
                .defaultSuccessUrl("/success") //重定向  和上面的不能同时存在,如果登录之前没有拦截网站,登录之后就会调整到设定页面,否则,跳转到拦截页面
                .failureForwardUrl("/fail") //登录失败跳转
前后端分量的情况(json传输)
  • 这里就不需要登录界面,登录成功或者识别的界面也不需要了
  • 返回的都是json信息,我们根据业务需要,自定义相关的业务信息
                .and()
                .formLogin()
                .successHandler((req,resp,authentication) ->{
                    resp.setContentType("application/json;charset=utf-8");
                    PrintWriter out = resp.getWriter();
                    out.write(new ObjectMapper().writeValueAsString(authentication.getPrincipal()));//返回的是登录信息
                    out.flush();
                    out.close();
                })
                
  • 登录失败,返回的json信息

                .failureHandler((req,resp,exception) ->{
                    resp.setContentType("application/json;charset=utf-8");
                    PrintWriter out = resp.getWriter();
                    out.write(new ObjectMapper().writeValueAsString(exception.getMessage()));//返回的信息错误的异常信息
                    out.flush();
                    out.close();
                })
                .permitAll()
  • 未登录时候,返回json提示信息
                .exceptionHandling()
                .authenticationEntryPoint((req, resp, exception) ->{
                    resp.setContentType("application/json;charset=utf-8");
                    PrintWriter out = resp.getWriter();
                    out.write(new ObjectMapper().writeValueAsString("尚未登录,请登录"));//返回的信息可以修改为json信息
                    out.flush();
                    out.close();
                });
  • 注销登录
               .and()
                .logout()
                .logoutUrl("/logout") //配置登录失败请求
                .logoutSuccessHandler((req,resp,authentication) ->{
                    resp.setContentType("application/json;charset=utf-8");
                    PrintWriter out = resp.getWriter();
                    out.write(new ObjectMapper().writeValueAsString("注销成功"));
                    out.flush();
                    out.close();
                })
                .permitAll()
注销接口
  • 注销的接口设置为/logout,默认是GET请求
  • 我们也可以使用POST请求,.logoutRequestMatcher(new AntPathRequestMatcher("/logout","POST"))
  • 清除认证clearAuthentication(true),默认就是true
  • 清除session信息,默认就是trueinvalidateHttpSession(true)
                .and()
                .logout()
                .logoutUrl("/logout") //配置登录失败请求
//                .logoutRequestMatcher(new AntPathRequestMatcher("/logout","POST")) //将登录失败的请求,从get方法,换为post方法
                .invalidateHttpSession(true)// 清除session信息  默认就是true
                .clearAuthentication(true) //清除认证 默认就是true
                .permitAll()
                .and()
                .csrf().disable(); //这里是为了方便测试

完整代码如下:

package com.brige.security;

import com.fasterxml.jackson.databind.ObjectMapper;
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.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.DelegatingPasswordEncoder;
import org.springframework.security.crypto.password.Md4PasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.util.matcher.AndRequestMatcher;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import java.io.PrintWriter;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    @Bean
    PasswordEncoder passwordEncoder(){
//        return new BCryptPasswordEncoder();
        return NoOpPasswordEncoder.getInstance();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("javaBoy")
                .password("123456")
                .roles("admin");
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/js/**","/css/**","/image/**");
    }

    //非前后端分离的写法
//    @Override
//    protected void configure(HttpSecurity http) throws Exception {
//        http.authorizeRequests()
//                .anyRequest().authenticated() //所有的访问都需要权限
//                .and()
//                .formLogin()
//                .loginPage("/login")
//                .loginProcessingUrl("/dologin")
//                .usernameParameter("name")
//                .passwordParameter("pwd")
                .successForwardUrl("/success") //服务端跳转  登录成功后,跳转到success页面
//                .defaultSuccessUrl("/success") //重定向  和上面的不能同时存在,如果登录之前没有拦截网站,登录之后就会调整到设定页面,否则,跳转到拦截页面
//                .failureForwardUrl("/file") //登录失败跳转
//                .and()
//                .logout()
//                .logoutUrl("/logout") //配置登录失败请求
                .logoutRequestMatcher(new AntPathRequestMatcher("/logout","POST")) //将登录失败的请求,从get方法,换为post方法
//                .invalidateHttpSession(true)// 清除session信息  默认就是true
//                .clearAuthentication(true) //清除认证 默认就是true
//                .permitAll()
//                .and()
//                .csrf().disable();
//    }

    //前后端分离的写法
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .anyRequest().authenticated() //所有的访问都需要权限
                .and()
                .formLogin()
                .successHandler((req,resp,authentication) ->{
                    resp.setContentType("application/json;charset=utf-8");
                    PrintWriter out = resp.getWriter();
                    out.write(new ObjectMapper().writeValueAsString(authentication.getPrincipal()));//返回的是登录信息
                    out.flush();
                    out.close();
                })
                .failureHandler((req,resp,exception) ->{
                    resp.setContentType("application/json;charset=utf-8");
                    PrintWriter out = resp.getWriter();
                    out.write(new ObjectMapper().writeValueAsString(exception.getMessage()));//返回的信息错误的异常信息
                    out.flush();
                    out.close();
                })
                .permitAll()
                .and()
                .logout()
                .logoutUrl("/logout") //配置登录失败请求
                .logoutSuccessHandler((req,resp,authentication) ->{
                    resp.setContentType("application/json;charset=utf-8");
                    PrintWriter out = resp.getWriter();
                    out.write(new ObjectMapper().writeValueAsString("注销成功");
                    out.flush();
                    out.close();
                })
                .permitAll()
                .and()
                .csrf().disable()
                .exceptionHandling()
                .authenticationEntryPoint((req, resp, exception) ->{
                    resp.setContentType("application/json;charset=utf-8");
                    PrintWriter out = resp.getWriter();
                    out.write(new ObjectMapper().writeValueAsString("尚未登录,请登录"));//返回的信息可以修改为json信息
                    out.flush();
                    out.close();
                });
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值