如何响应Spring Security自己的未授权用户方式

时间:2016-03-24 02:34:50

标签: java spring spring-security

当用户输入错误的凭据时,我需要使用Spring安全过滤器中的一些JSON返回客户端http代码401。

安全问题:

<http pattern="/log/**" use-expressions="true" name="restSecurityFilterChain" create-session="stateless">
    <http-basic/>
    <intercept-url pattern="/**" access="hasRole('ROLE_USER')"/>
    <csrf disabled="true"/>
</http>

<authentication-manager>
    <authentication-provider ref="userService">
    </authentication-provider>
</authentication-manager>

认证提供者:

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String name = authentication.getName();
    String password = authentication.getCredentials().toString();

    User user = repository.getByNameAndPass(name, password);
    if (user == null) {
        name = "NotAuthorised";
        password = "";
    }
    List<GrantedAuthority> grantedAuths = new ArrayList<>();
    grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER"));
    Authentication auth = new UsernamePasswordAuthenticationToken(name, password, grantedAuths);
    return auth;
}

@Override
public boolean supports(Class<?> authentication) {
    return authentication.equals(UsernamePasswordAuthenticationToken.class);
}

这里我记录了错误的用户,因为&#34; NotAuthorised&#34;到我的控制器。

控制器:

@RequestMapping(value = "/log", method = RequestMethod.GET)
public ResponseEntity<Map<String,Object>>  getAll(@RequestParam(value = "page", required = false) Integer page,
                                 @RequestParam(value = "size", required = false) Integer size) {

    Map<String, Object> resultMap = new HashMap<>();
    String loggedUser = userService.getLoggedUser();
    if ("NotAuthorised".equals(loggedUser)) {
        LOG.info("authtoriation error");
        resultMap.put("message","Access denied");
        return new ResponseEntity<>(resultMap, HttpStatus.UNAUTHORIZED);
    }

    LOG.info("getAll for logmessages ");
    resultMap.put("logs", logMessageService.getLogMessagesDT(logMessageService.getPage(page == null ? 0 :
            page.intValue(), size == null ? 0 : size.intValue())) );

    return new ResponseEntity<>(resultMap, HttpStatus.OK);
}

在输入错误的凭据后,Spring请求凭证两次,并返回状态0&amp; &#34;&#34; JSON:

return new ResponseEntity<>(resultMap, HttpStatus.UNAUTHORIZED);

如果我没有返回401状态 - 一切正常。

0 个答案:

没有答案