gpt4 book ai didi

json - grails spring 安全休息状态 401 重定向到 Controller 的操作以抛出自定义错误消息

转载 作者:行者123 更新时间:2023-12-05 01:04:26 25 4
gpt4 key购买 nike

我们正在使用 spring-security-core:2.0-RC4 , spring-security-rest:1.4.0 plugin与 chalice 2.4.2。他们两个都工作正常。当用户输入无效凭证时,spring-security-rest:1.4.0插件给出401,这是在Config.groovy中配置的

grails.plugin.springsecurity.rest.login.failureStatusCode =  401

这是控制台输出的小片段
rest.RestAuthenticationFilter  - Actual URI is /api/login; endpoint URL is /api/login
rest.RestAuthenticationFilter - Applying authentication filter to this request
credentials.DefaultJsonPayloadCredentialsExtractor - Extracted credentials from JSON payload. Username: admin@asdasdmopi.com, password: [PROTECTED]
rest.RestAuthenticationFilter - Trying to authenticate the request
authentication.ProviderManager - Authentication attempt using org.springframework.security.authentication.dao.DaoAuthenticationProvider
dao.DaoAuthenticationProvider - User 'admin@something.com' not found
rest.RestAuthenticationFilter - Authentication failed: Bad credentials
rest.RestAuthenticationFailureHandler - Setting status code to 401
context.HttpSessionSecurityContextRepository - SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
context.SecurityContextPersistenceFilter - SecurityContextHolder now cleared, as request processing completed

现在没有错误消息或响应,只是向客户端发送状态 401。现在我试图在有 401 状态时发送错误响应。

在 UrlMappings.groovy 中添加了以下行
"401"(controller:'unauthorized',action:'sendErrorResponse')

创建了 UnauthorizedController.groovy 并添加了 sendErrorResponse() 如下
def sendErrorResponse() { 
try{
int errorCode = grailsApplication.config.customExceptions.account.fourZeroOne.loginNotAuthorized.errorCode
int status = grailsApplication.config.customExceptions.account.fourZeroOne.loginNotAuthorized.status
String message = grailsApplication.config.customExceptions.account.fourZeroOne.loginNotAuthorized.message
String extendedMessage = grailsApplication.config.customExceptions.account.fourZeroOne.loginNotAuthorized.extendedMessage
String moreInfo = grailsApplication.config.customExceptions.account.fourZeroOne.loginNotAuthorized.moreInfo

throw new AccountException(status,errorCode,message,extendedMessage,moreInfo)
}catch(AccountException e){
log.error e.errorResponse()
response.setStatus(e.errorResponse().status)
render e.errorResponse()
}
}

我的想法是在 401 上将调用 Controller 并且该方法将呈现错误响应,但它不起作用。

我的方法对吗?

任何其他最佳实践或想法来实现这一点?

任何指向正确方向的指针都值得赞赏。

万分感谢。

最佳答案

您需要覆盖 grails.plugin.springsecurity.rest.RestAuthenticationFailureHandler bean 与您自己的自定义版本。

它可以是这样的:

@Slf4j
@CompileStatic
class CustomRestAuthenticationFailureHandler implements AuthenticationFailureHandler {

/**
* Configurable status code, by default: conf.rest.login.failureStatusCode?:HttpServletResponse.SC_FORBIDDEN
*/
Integer statusCode

MessageSource messageSource

/**
* Called when an authentication attempt fails.
* @param request the request during which the authentication attempt occurred.
* @param response the response.
* @param exception the exception which was thrown to reject the authentication request.
*/
void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
response.setStatus(statusCode)
response.addHeader('WWW-Authenticate', Holders.config.get("grails.plugin.springsecurity.rest.token.validation.headerName").toString())
def errorMessage
if (exception instanceof AccountExpiredException) {
errorMessage = messageSource.getMessage("springSecurity.errors.login.expired", null as Object[], LocaleContextHolder.getLocale())
} else if (exception instanceof CredentialsExpiredException) {
errorMessage = messageSource.getMessage("springSecurity.errors.login.passwordExpired", null as Object[], LocaleContextHolder.getLocale())
} else if (exception instanceof DisabledException) {
errorMessage = messageSource.getMessage("springSecurity.errors.login.disabled", null as Object[], LocaleContextHolder.getLocale())
} else if (exception instanceof LockedException) {
errorMessage = messageSource.getMessage("springSecurity.errors.login.locked", null as Object[], LocaleContextHolder.getLocale())
} else {
errorMessage = messageSource.getMessage("springSecurity.errors.login.fail", null as Object[], LocaleContextHolder.getLocale())
}
PrintWriter out = response.getWriter()
response.setContentType("aplication/json")
response.setCharacterEncoding("UTF-8");
out.print(new JsonBuilder([message: errorMessage]).toString());
out.flush();
}
}

在你的 resources.groovy 你应该有
restAuthenticationFailureHandler(CustomRestAuthenticationFailureHandler) {
statusCode = HttpServletResponse.SC_UNAUTHORIZED
messageSource = ref("messageSource")
}

关于json - grails spring 安全休息状态 401 重定向到 Controller 的操作以抛出自定义错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26652234/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com