Spring Boot整合Spring Security入门案例

这是默认登陆
HelloController控制层
在这里插入图片描述
配置类

package com.sxt.springsecuritytest.config;
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.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * 配置账号验证和请求授权
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 需求lyb只能访问admin user ,张三只能访问user
     *
     * 授权方法
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests() //开启授权请求
                .antMatchers("/admin/**") //控制层路径下的请求匹配
                .hasRole("admin")//一个角色和admin/路径绑定
                .antMatchers("/user/**") //控制层路径下的请求匹配
                .hasAnyRole("admin","user")  //二个角色和user/路径绑定
                .anyRequest().authenticated()//其它的请求要登陆后才能访问
                .and()
                .formLogin().permitAll(); //登陆表单可以登陆
    }
    /**
     * 账号密码和角色验证方法
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()//开启身份验证
                .withUser("lyb")//账号
                 .password("$2a$10$JJEsTA5nvH6Z9s.vl7LyqOYIcdVI3x8uooSh7.oTI3ZoDNXt.arsi") //密码
                  .roles("admin") //lyb是这角色
                  .and()
                .withUser("zhangsan")
                .password("$2a$10$JJEsTA5nvH6Z9s.vl7LyqOYIcdVI3x8uooSh7.oTI3ZoDNXt.arsi")
                .roles("user"); //zhangsan是这角色

    }
    /**
     *  对密码进行加密与密码匹配
     * @return
     */
    @Bean
    PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}

需求lyb只能访问admin user ,张三只能访问user
页面输入http://localhost:8080
lyb账号登陆
http://localhost:8080/hello 访问报404没这路径请求
http://localhost:8080/admin 访问成功
http://localhost:8080/user 访问成功
zhangsan登陆
http://localhost:8080/user 访问成功
http://localhost:8080/admin 报403不具备角色

自定义请求登陆,多写了二个处理器

package com.sxt.springsecuritytest.config;
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.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * 配置账号验证和请求授权
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 授权方法
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests() //开启授权请求
                .antMatchers("/admin/**") //控制层路径下的请求匹配
                .hasRole("admin")//一个角色和admin/路径绑定
                .antMatchers("/user/**") //控制层路径下的请求匹配
                .hasAnyRole("admin","user")  //二个角色和user/路径绑定
                .anyRequest().authenticated()//其它的请求要登陆后才能访问
                .and()
                .formLogin()
///////////////////////////////////////////////////////
                .passwordParameter("password")//自定义登陆时密码的key
                .usernameParameter("username")//自定义登陆时用户名的key
                .loginProcessingUrl("/doLogin") //页面输入登陆接口请求
                .loginPage("/login") //登陆页面

                 //登录成功的处理器
                .successHandler(new AuthenticationSuccessHandler() {
                    /**
                     * 登陆成功返回一段json数据
                     * @param request 请求
                     * @param response 响应
                     * @param authentication 身份验证
                     * @throws IOException
                     * @throws ServletException
                     */
                    @Override
                    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
                        response.setContentType("application/json;charset=utf-8");//响应格式
                        Map<String, Object> map = new HashMap<>();//保存到集合
                        map.put("status",200);//成功200
                        map.put("msg","登录成功");
                        map.put("obj",authentication.getPrincipal()); //获取用户信息
                        PrintWriter out = response.getWriter(); //获取响应流对象
                        out.write(new ObjectMapper().writeValueAsString(map)); //集合里值输出到页面
                        out.flush();//刷新
                        out.close();//关闭
                    }
                })

                //登陆失败的处理器
                //AuthenticationException 登陆失败的异常类
                .failureHandler(new AuthenticationFailureHandler() {
                    @Override
                    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
                            response.setContentType("application/json;charset=utf-8");
                        Map<String, Object> map = new HashMap<String,Object>();
                        map.put("status","500");
                        map.put("msg","登陆失败");
                        PrintWriter writer = response.getWriter();
                        writer.write(new ObjectMapper().writeValueAsString(map));
                        writer.flush();
                        writer.close();
                    }
                })
                 .permitAll()
                 .and()
                 .csrf().disable();//安全关闭posm测试
//
    }
    /**
     * 账号密码和角色验证方法
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()//开启身份验证
                .withUser("lyb")//账号
                 .password("$2a$10$JJEsTA5nvH6Z9s.vl7LyqOYIcdVI3x8uooSh7.oTI3ZoDNXt.arsi") //密码
                  .roles("admin") //lyb是这角色
                  .and()
                .withUser("zhangsan")
                .password("$2a$10$JJEsTA5nvH6Z9s.vl7LyqOYIcdVI3x8uooSh7.oTI3ZoDNXt.arsi")
                .roles("user"); //zhangsan是这角色

    }
    /**
     *  对密码进行加密与密码匹配
     * @return
     */
    @Bean
    PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}

登陆
在这里插入图片描述
登陆后可访问
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Java语录精选

你的鼓励是我坚持下去的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值