Spring 没有 xml 配置的具有基本身份验证的其余 Web 服务
Spring rest webservice with BasicAuth without xml configuration
我想知道是否可以使用 BasicAuth 创建 Spring Web 服务而不创建 web.xml 或任何基于 xml 的配置内容。
我看到了很多关于 xml 的教程,但我想用 class 配置方式来做。
嗯,很抱歉,这可能不准确,因为我不再使用此实现,我用基于 EE 的模型代替了,但是......在这里和我一起工作。 :)
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.passwordEncoder(passwordEncoder())
.withUser("fooserviceuser").password("aDvfxB.Sj2B/QznFRw85FenDvhUGglWWgOR7mmal/jNImhdHQRJgi").roles("USER");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/**").hasRole("USER")
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
@Bean
public BCryptPasswordEncoder passwordEncoder(){
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
return encoder;
}
}
您还需要一个初始化程序来挂接到容器中,例如 --
public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
}
这使用 bcrypt 进行密码散列。抱歉,这不是工作代码,但我认为这里有足够的内容让您走上正轨! Google 类似的代码片段,它们就在那里。
我想知道是否可以使用 BasicAuth 创建 Spring Web 服务而不创建 web.xml 或任何基于 xml 的配置内容。
我看到了很多关于 xml 的教程,但我想用 class 配置方式来做。
嗯,很抱歉,这可能不准确,因为我不再使用此实现,我用基于 EE 的模型代替了,但是......在这里和我一起工作。 :)
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.passwordEncoder(passwordEncoder())
.withUser("fooserviceuser").password("aDvfxB.Sj2B/QznFRw85FenDvhUGglWWgOR7mmal/jNImhdHQRJgi").roles("USER");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/**").hasRole("USER")
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
@Bean
public BCryptPasswordEncoder passwordEncoder(){
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
return encoder;
}
}
您还需要一个初始化程序来挂接到容器中,例如 --
public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
}
这使用 bcrypt 进行密码散列。抱歉,这不是工作代码,但我认为这里有足够的内容让您走上正轨! Google 类似的代码片段,它们就在那里。