使用Spring Boot 2.0的Spring Security:保护端点

本文介绍了如何在复杂的Spring Boot应用中使用Spring Security进行端点安全策略配置。默认配置保护所有端点,但有时需要设定特定端点的访问权限。通过HttpSecurity类,我们可以自定义哪些端点公开,哪些受保护,并提供公共访问的欢迎消息端点。同时,确保登录和注销端点的可用性。
摘要由CSDN通过智能技术生成

到目前为止,在以前的文章中,我们已经使用默认的spring安全配置对端点和控制器进行了安全保护。

当Spring Security在类路径上时,默认情况下自动配置会保护所有端点。

当涉及到复杂的应用程序时,我们需要每个端点使用不同的安全策略。 我们需要配置哪些端点应受到保护,哪些类型的用户应能够访问该端点以及应公开的端点。

一个很好的例子是端点,它将向用户显示欢迎消息。

package com.gkatzioura.security.securityendpoints.controller;

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

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class IndexController {

    @GetMapping(path = "welcome")
    public String getMessage() {

        return "Welcome to the application";
    }
}

关于您的应用程序已经受到保护的事实,您需要提供对该端点的公共访问。

为了做到这一点,spring为我们提供了HttpSecurity类。 通过扩展WebSecurityConfigurerAdapter我们可以配置应该保护的端点和应该是公共的端点。

因此,让我们创建WebSecurityConfigurerAdapter配置。

package com.gkatzioura.security.securityendpoints.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers("/welcome").permitAll()
            .anyRequest().authenticated()
            .and()
            .formLogin()
            .permitAll()
            .and()
            .logout()
            .permitAll();
    }
}

因此,让我们通过调用authorizeRequests函数将其分为几个部分。 我们有一个http配置器,可以添加我们想要公开或保护的端点。

通过调用antMatchers函数,我们可以传递一组蚂蚁模式。 应用的功能将为在antmatchers中指定的每个端点创建一个规则。

下一个功能是anyRequest 。 验证后的规则将应用于收到的任何请求。

最后但并非最不重要的一点是spring带有默认的登录表单和默认的注销端点。 为了使登录和注销变得可行,我们必须允许访问这些端点。

因此,最终结果将是可以公开访问欢迎端点,用于登录和注销端点的预配置表单。

翻译自: https://www.javacodegeeks.com/2018/07/spring-security-boot-2-securing-endpoints.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值