Spring Boot 整合 Spring Security(配置登录/登出)

Spring Boot 整合 Spring Security ,配置登录/登出,如:登录接口,登录成功或失败后的响应等。

1 创建工程

创建 Spring Boot 项目 spring-boot-springsecurity-login ,添加 Web/Spring Security 依赖,如下:

最终的依赖如下:

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

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

2 配置 Spring Security

新增 SecurityConfig 配置类,如下:

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Bean
    PasswordEncoder passwordEncoder() {
//        return NoOpPasswordEncoder.getInstance();// 密码不加密
        return new BCryptPasswordEncoder();// 密码加密
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 在内存中配置 2 个用户
        /*auth.inMemoryAuthentication()
                .withUser("admin").password("123456").roles("admin")
                .and()
                .withUser("user").password("123456").roles("user");// 密码不加密*/

        auth.inMemoryAuthentication()
                .withUser("admin").password("$2a$10$fB2UU8iJmXsjpdk6T6hGMup8uNcJnOGwo2.QGR.e3qjIsdPYaS4LO").roles("admin")
                .and()
                .withUser("user").password("$2a$10$3TQ2HO/Xz1bVHw5nlfYTBON2TDJsQ0FMDwAS81uh7D.i9ax5DR46q").roles("user");// 密码加密
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 开启登录配置
        http.authorizeRequests()
                // 表示 admin 角色能访问
                .antMatchers("/admin/**").hasRole("admin")
                // 表示 admin 或 user 角色都能访问
                // .antMatchers("/user/**").hasAnyRole("admin", "user")
                // 表示 admin 或 user 角色都能访问
                .antMatchers("/user/**").access("hasAnyRole('admin','user')")
                // 表示剩余的其他接口,登录之后就能访问
                .anyRequest().authenticated()
                .and()
                .formLogin()
                // 表示登录页的地址,例如当你访问一个需要登录后才能访问的资源时,系统就会自动给你通过【重定向】跳转到这个页面上来
                .loginPage("/login")
                // 表示处理登录请求的接口地址,默认为 /login
                .loginProcessingUrl("/doLogin")
                // 定义登录时,用户名的 key,默认为 username
                .usernameParameter("uname")
                // 定义登录时,密码的 key,默认为 password
                .passwordParameter("passwd")
                // 登录成功的处理器
                .successHandler(new AuthenticationSuccessHandler() {
                    @Override
                    public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication authentication) throws IOException, ServletException {
                        resp.setContentType("application/json;charset=utf-8");
                        PrintWriter out = resp.getWriter();
                        Map<String, Object> map = new HashMap<>();
                        map.put("status", 200);
                        map.put("msg", authentication.getPrincipal());
                        out.write(new ObjectMapper().writeValueAsString(map));
                        out.flush();
                        out.close();
                    }
                })
                // 登录失败的处理器
                .failureHandler(new AuthenticationFailureHandler() {
                    @Override
                    public void onAuthenticationFailure(HttpServletRequest req, HttpServletResponse resp, AuthenticationException e) throws IOException, ServletException {
                        resp.setContentType("application/json;charset=utf-8");
                        PrintWriter out = resp.getWriter();
                        Map<String, Object> map = new HashMap<>();
                        map.put("status", 401);
                        if (e instanceof LockedException) {
                            map.put("msg", "账户被锁定,登录失败!");
                        } else if (e instanceof BadCredentialsException) {
                            map.put("msg", "用户名或密码输入错误,登录失败!");
                        } else if (e instanceof DisabledException) {
                            map.put("msg", "账户被禁用,登录失败!");
                        } else if (e instanceof AccountExpiredException) {
                            map.put("msg", "账户过期,登录失败!");
                        } else if (e instanceof CredentialsExpiredException) {
                            map.put("msg", "密码过期,登录失败!");
                        } else {
                            map.put("msg", "登录失败!");
                        }
                        out.write(new ObjectMapper().writeValueAsString(map));
                        out.flush();
                        out.close();
                    }
                })
                // 和表单登录相关的接口统统都直接通过
                .permitAll()
                .and()
                .logout()
                .logoutUrl("/logout")
                // 登出成功的处理器
                .logoutSuccessHandler(new LogoutSuccessHandler() {
                    @Override
                    public void onLogoutSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication authentication) throws IOException, ServletException {
                        resp.setContentType("application/json;charset=utf-8");
                        PrintWriter out = resp.getWriter();
                        Map<String, Object> map = new HashMap<>();
                        map.put("status", 200);
                        map.put("msg", "注销登录成功!");
                        out.write(new ObjectMapper().writeValueAsString(map));
                        out.flush();
                        out.close();
                    }
                })
                .permitAll()
                .and()
                .csrf().disable()
                .exceptionHandling()
                // 无访问权限的处理器
                .accessDeniedHandler(new AccessDeniedHandler() {
                    @Override
                    public void handle(HttpServletRequest req, HttpServletResponse resp, AccessDeniedException e) throws IOException, ServletException {
                        resp.setContentType("application/json;charset=utf-8");
                        PrintWriter out = resp.getWriter();
                        Map<String, Object> map = new HashMap<>();
                        map.put("status", 403);
                        map.put("msg", "无访问权限!");
                        out.write(new ObjectMapper().writeValueAsString(map));
                        out.flush();
                        out.close();
                    }
                })
                // 默认情况下用户直接访问一个需要认证之后才可以访问的请求时,会被重定向到.loginPage("/login"),前后端分离时会导致跨域。
                // 增加如下配置后,就不会发生重定向操作了,服务端会直接给浏览器一个 JSON 提示
                .authenticationEntryPoint(new AuthenticationEntryPoint() {
                    @Override
                    public void commence(HttpServletRequest req, HttpServletResponse resp, AuthenticationException authException) throws IOException, ServletException {
                        resp.setContentType("application/json;charset=utf-8");
                        PrintWriter out = resp.getWriter();
                        Map<String, Object> map = new HashMap<>();
                        map.put("status", 401);
                        if (authException instanceof InsufficientAuthenticationException) {
                            map.put("msg", "访问失败,请先登录!");
                        } else {
                            map.put("msg", "访问失败!");
                        }
                        out.write(new ObjectMapper().writeValueAsString(map));
                        out.flush();
                        out.close();
                    }
                });
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        // 配置不需要拦截的请求地址,即该地址不走 Spring Security 过滤器链
        web.ignoring().antMatchers("/vercode");
    }
}

3 测试

新增 HelloController 测试类,如下:

@RestController
public class HelloController {
    @GetMapping("/hello")
    public String hello() {
        return "hello";
    }

    @GetMapping("/admin/hello")
    public String admin() {
        return "hello admin";
    }

    @GetMapping("/user/hello")
    public String user() {
        return "hello user";
    }

    @GetMapping("/login")
    public String login() {
        return "please login";
    }
}

项目启动之后,用 Postman 完成测试,如下:

访问 /hello 接口,提示先登录。

访问 /doLogin 接口登录失败,因为 key 不对。

用自定义的 key 访问 /doLogin 接口登录成功。

再访问 /hello 接口,返回正常。



扫码关注微信公众号 程序员35 ,获取最新技术干货,畅聊 #程序员的35,35的程序员# 。独立站点:https://cxy35.com

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
OAuth2.0是一种常用的认证授权机制,Spring SecuritySpring框架中的安全模块,可以实现OAuth2.0认证。本文将介绍如何利用Spring Boot 2.0和Spring Security实现简单的OAuth2.0认证方式1。 1. 添加依赖 在项目的pom.xml文件中添加以下依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.security.oauth</groupId> <artifactId>spring-security-oauth2</artifactId> <version>2.3.7.RELEASE</version> </dependency> ``` 其中,spring-boot-starter-securitySpring Boot中包含Spring Security的依赖,spring-security-oauth2是Spring Security中实现OAuth2.0的依赖。 2. 配置Spring SecuritySpring Boot应用中,可以通过application.properties或application.yml文件来配置Spring Security。在本文中,我们将使用application.yml文件来配置Spring Security。 ``` spring: security: oauth2: client: registration: custom-client: client-id: custom-client-id client-secret: custom-client-secret authorization-grant-type: authorization_code redirect-uri: '{baseUrl}/login/oauth2/code/{registrationId}' scope: - read - write provider: custom-provider: authorization-uri: https://custom-provider.com/oauth2/auth token-uri: https://custom-provider.com/oauth2/token user-info-uri: https://custom-provider.com/userinfo user-name-attribute: sub ``` 其中,我们定义了一个名为custom-client的OAuth2.0客户端,它的客户端ID和客户端密钥分别为custom-client-id和custom-client-secret,授权方式为authorization_code,重定向URI为{baseUrl}/login/oauth2/code/{registrationId},授权范围为read和write。 同时,我们定义了一个名为custom-provider的OAuth2.0提供者,它的授权URI、令牌URI、用户信息URI和用户名属性分别为https://custom-provider.com/oauth2/auth、https://custom-provider.com/oauth2/token、https://custom-provider.com/userinfo和sub。 3. 配置OAuth2.0登录Spring Security中,可以通过配置HttpSecurity对象来定义登录、授权等行为。在本文中,我们将使用configure方法来配置HttpSecurity对象。 ``` @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/", "/home").permitAll() .anyRequest().authenticated() .and() .oauth2Login() .loginPage("/login") .defaultSuccessURL("/dashboard") .and() .logout() .logoutSuccessUrl("/") .permitAll(); } } ``` 其中,我们使用了authorizeRequests方法来设置授权规则,任何请求都需要进行认证,除了根路径和home路径。我们还使用了oauth2Login方法来设置OAuth2.0登录的相关配置,包括登录页面、默认成功URL等。最后,我们使用了logout方法来设置登出的相关配置,包括成功URL等。 4. 配置用户信息 在OAuth2.0认证中,用户信息通常由OAuth2.0提供者来维护。在Spring Security中,可以通过实现UserInfoRestTemplateFactory接口来获取用户信息。 ``` @Configuration public class OAuth2Config { @Bean public OAuth2UserService<OAuth2UserRequest, OAuth2User> oAuth2UserService() { return new DefaultOAuth2UserService(); } @Bean public UserInfoRestTemplateFactory userInfoRestTemplateFactory() { return new CustomUserInfoRestTemplateFactory(); } } ``` 其中,我们使用了DefaultOAuth2UserService来获取用户信息,同时使用了CustomUserInfoRestTemplateFactory来创建RestTemplate对象。 5. 编写测试 最后,我们可以编写一个简单的测试来验证OAuth2.0认证是否生效。 ``` @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @AutoConfigureMockMvc public class OAuth2Test { @Autowired private MockMvc mockMvc; @Test public void testOAuth2Login() throws Exception { mockMvc.perform(get("/login")) .andExpect(status().isOk()) .andExpect(content().string(containsString("Login with custom-provider"))) .andReturn(); } } ``` 在测试中,我们使用MockMvc对象模拟访问/login路径,期望返回200状态码,并且页面内容中包含“Login with custom-provider”的字符串。 至此,我们已经成功地利用Spring Boot 2.0和Spring Security实现了简单的OAuth2.0认证方式1。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值