我将此代码用于Rest API身份验证:
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
Optional<String> basicToken = Optional.ofNullable(request.getHeader(HttpHeaders.AUTHORIZATION))
.filter(v -> v.startsWith("Basic"))
.map(v -> v.split("\\s+")).filter(a -> a.length == 2).map(a -> a[1]);
if (!basicToken.isPresent()) {
return sendAuthError(response);
}
byte[] bytes = Base64Utils.decodeFromString(basicToken.get());
String namePassword = new String(bytes, StandardCharsets.UTF_8);
int i = namePassword.indexOf(':');
if (i < 0) {
return sendAuthError(response);
}
String name = namePassword.substring(0, i);
String password = namePassword.substring(i + 1);
// Optional<String> clientId = authenticationService.authenticate(name, password, request.getRemoteAddr());
Merchants merchant = authenticationService.authenticateMerchant(name, password, request.getRemoteAddr());
if (merchant == null) {
return sendAuthError(response);
}
request.setAttribute(CURRENT_CLIENT_ID_ATTRIBUTE, merchant.getId());
return true;
}
我如何使用Spring Security重写代码以获得相同的结果,但是对于不同的链接进行身份验证?例如:
localhost:8080/v1/notification - requests should NOT be authenticated.
localhost:8080/v1/request - requests should be authenticated.
在这里你可以找到一个工作项目https://github.com/angeloimm/springbasicauth
我知道在pom.xml文件中有很多无用的依赖项,但我从一个已经存在的项目开始,我没有时间去除它
基本上你必须:
让我解释一下代码。
Spring MVC配置:
@Configuration
@EnableWebMvc
@ComponentScan(basePackages= {"it.olegna.test.basic"})
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void configureMessageConverters(final List<HttpMessageConverter<?>> converters) {
converters.add(new MappingJackson2HttpMessageConverter());
}
}
在这里,我们不做任何其他配置spring MVC的事情,告诉它在哪里找到控制器等等,并使用单个消息转换器; MappingJackson2HttpMessageConverter
以产生JSON响应
Spring安全配置:
@Configuration
@EnableWebSecurity
@Import(value= {WebMvcConfig.class})
public class WebSecConfig extends WebSecurityConfigurerAdapter {
@Autowired private RestAuthEntryPoint authenticationEntryPoint;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("test")
.password(passwordEncoder().encode("testpwd"))
.authorities("ROLE_USER");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/securityNone")
.permitAll()
.anyRequest()
.authenticated()
.and()
.httpBasic()
.authenticationEntryPoint(authenticationEntryPoint);
}
@Bean
public PasswordEncoder passwordEncoder() {
return NoOpPasswordEncoder.getInstance();
}
}
这里我们配置Spring Security,以便对除了以securityNone开头的请求之外的所有请求使用HTTP基本身份验证。我们使用NoOpPasswordEncoder
来编码提供的密码;这个PasswrodEncoder绝对没有任何东西......它留下了passwrod原样。
其余的入口点:
@Component
public class RestAuthEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
}
}
此入口点禁用所有不包含Authentication标头的请求
SimpleDto:一个非常简单的DTO,代表控制器的JSON答案
public class SimpleDto implements Serializable {
private static final long serialVersionUID = 1616554176392794288L;
private String simpleDtoName;
public SimpleDto() {
super();
}
public SimpleDto(String simpleDtoName) {
super();
this.simpleDtoName = simpleDtoName;
}
public String getSimpleDtoName() {
return simpleDtoName;
}
public void setSimpleDtoName(String simpleDtoName) {
this.simpleDtoName = simpleDtoName;
}
}
TestBasicController:一个非常简单的控制器
@RestController
@RequestMapping(value= {"/rest"})
public class TestBasicController {
@RequestMapping(value= {"/simple"}, method= {RequestMethod.GET}, produces= {MediaType.APPLICATION_JSON_UTF8_VALUE})
public ResponseEntity<List<SimpleDto>> getSimpleAnswer()
{
List<SimpleDto> payload = new ArrayList<>();
for(int i= 0; i < 5; i++)
{
payload.add(new SimpleDto(UUID.randomUUID().toString()));
}
return ResponseEntity.ok().body(payload);
}
}
因此,如果您使用邮递员或任何其他测试人员尝试此项目,您可以有2个方案:
假设您想要调用URL http://localhost:8080/test_basic/rest/simple而不传递Authentication头。 HTTP状态代码将是401 Unauthorized
这意味着需要Authentication Header
通过将此标头添加到请求Authorization Basic dGVzdDp0ZXN0cHdk
,所有工作都很好注意,字符串dGVzdDp0ZXN0cHdk
是字符串username:password
的Base64编码;在我们的例子中是inMemoryAuthentication中定义的test:testpwd
的Base64编码
我希望这很有用
安杰洛
WEB安全用户数据服务
要将Spring安全性配置为从DB检索用户详细信息,您必须执行以下操作:
像这样创建一个org.springframework.security.core.userdetails.UserDetailsService实现:
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
private BasicService svc;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
BasicUser result = svc.findByUsername(username);
if( result == null )
{
throw new UsernameNotFoundException("No user found with username "+username);
}
return result;
}
}
将它注入spring安全配置并使用它如下:
public class WebSecConfig extends WebSecurityConfigurerAdapter {
@Autowired private RestAuthEntryPoint authenticationEntryPoint;
@Autowired
UserDetailsService userDetailsService;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
// auth
// .inMemoryAuthentication()
// .withUser("test")
// .password(passwordEncoder().encode("testpwd"))
// .authorities("ROLE_USER");
auth.userDetailsService(userDetailsService);
auth.authenticationProvider(authenticationProvider());
}
@Bean
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
authenticationProvider.setUserDetailsService(userDetailsService);
authenticationProvider.setPasswordEncoder(passwordEncoder());
return authenticationProvider;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/securityNone")
.permitAll()
.anyRequest()
.authenticated()
.and()
.httpBasic()
.authenticationEntryPoint(authenticationEntryPoint);
}
@Bean
public PasswordEncoder passwordEncoder() {
return NoOpPasswordEncoder.getInstance();
}
}
我在我提供的github链接上推送了代码。在那里你可以找到一个完整的工作示例基于:
随意适应您自己的场景
您可以使用各种网站上描述的默认弹簧安全配置,例如baeldung.com或mkyong.com。你的样本中的诀窍似乎是获得Merchant
的号召。根据authenticationService
和Merchant
对象的复杂性,您可以使用以下代码,也可以实现Facade以获得类似的行为。
@Autowired
public void authenticationManager(AuthenticationManagerBuilder auth) {
auth.authenticationProvider(new AuthenticationProvider() {
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
Merchants merchant = authenticationService.authenticateMerchant(name, password, request.getRemoteAddr());
if(merchant == null) {
throw new AuthenticationException("No Merchant found.");
}
return new UsernamePasswordAuthenticationToken(name, password, merchant.getAuthorities());
}
@Override
public boolean supports(Class<?> authentication) {
return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication));
}
});
}
如果需要,可以通过单独的过滤器设置请求上的属性,该过滤器从Principal
获取SecurityContext
并将其作为属性放在请求上。