如何在 Spring 引导中指定安全约束和安全角色 [替换 web.xml]



我有一个需要使用应用程序服务器(Weblogic)并实现安全性的情况。我们正在将项目从弹簧转移到弹簧启动由于 Spring 启动没有任何 web.xml我如何通过 java 代码编写等效的安全约束。

<security-constraint>
        <web-resource-collection>
            <web-resource-name>rest-application</web-resource-name>
            <url-pattern>/*</url-pattern>
        </web-resource-collection>
        <auth-constraint>
            <role-name>xyz</role-name>
        </auth-constraint>
        <user-data-constraint>
            <transport-guarantee>CONFIDENTIAL</transport-guarantee>
        </user-data-constraint>
</security-constraint>
<Security-role>
<role-name>xyz></role-name>
</security-role>
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>abc</realm-name>
</login-config

Weblogic.xml将具有以下配置

<security-role-assignment>
<role-name>xyz</role-name>
<principal-name>pars</principal-name>
</security-role-assignment>

您可以使用具有基本身份验证的 Java 配置来配置 Spring 安全性。确保添加 Spring 安全依赖项。

替换您正在使用的用户/密码以及角色和密码算法。

@Configuration
@EnableWebSecurity
public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
          .withUser("user1").password(passwordEncoder().encode("user1Pass"))
          .authorities("ROLE_USER");
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
          .antMatchers("/public/paths").permitAll()
          .anyRequest().authenticated()
          .and()
          .httpBasic()
    }
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

最新更新