gpt4 book ai didi

java - 使用 Spring Security 'hasPermission()' 在未经授权的 REST 服务请求上返回 JSON

转载 作者:搜寻专家 更新时间:2023-10-31 20:02:27 24 4
gpt4 key购买 nike

我正在使用 Spring 安全实现方法级限制/授权(在 REST 服务 上)。
我使用了 spring 表达式语言并实现了自定义 Expression Evaluator。

它对我来说很好用。但是,如果未经授权的用户试图访问该服务,它会以登录页面作为响应。由于我的应用程序仅基于 REST,因此我只想为所有请求返回 JSON 数据。

如何让它返回 JSON 而不是登录页面?(例如:{status : Denied})

这是代码片段:

自定义评估器

public boolean hasPermission(Authentication authentication, Object userId, Object permissionId) {
List<String> permList = new MyDAO().getPermissionsForUser((String) userId);
if(permList.contains(((String) permissionId))){
return true;
}else{
return false;
}
}

服务

@PreAuthorize("hasPermission(#userId, '3')")
public String testAuthorization(Object obj, String userId){

System.out.println("Has access to the service method....");

return "success";
}

Controller

public @ResponseBody String testAuthorization(Object o,@RequestParam("userId") String userId){
System.out.println("User ID = "+userId);
String abc = service.testAuthorization(o,userId);
return "{\"status\":\"success\"}";
}

spring-security.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:security="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.0.xsd">


<security:global-method-security secured-annotations="enabled" pre-post-annotations="enabled">
<security:expression-handler ref="expressionHandler"/>
</security:global-method-security>

<!-- This is where we configure Spring-Security -->
<security:http auto-config="true" use-expressions="true" access-denied-page="/auth/auth/denied" >
<security:intercept-url pattern="/auth/auth/login" access="permitAll"/>
<security:intercept-url pattern="/auth/main/admin" access="hasRole('ROLE_ADMIN')"/>
<security:intercept-url pattern="/auth/main/common" access="hasRole('ROLE_USER')"/>


</security:http>

<security:authentication-manager>
<security:authentication-provider user-service-ref="customUserDetailsService">
<security:password-encoder ref="passwordEncoder"/>
</security:authentication-provider>
</security:authentication-manager>

<!-- Use a Md5 encoder since the user's passwords are stored as Md5 in the database -->
<bean class="org.springframework.security.authentication.encoding.Md5PasswordEncoder" id="passwordEncoder"/>

<!-- A custom service where Spring will retrieve users and their corresponding access levels -->
<bean id="customUserDetailsService" class="com.cjl.security.service.CustomUserDetailsService"/>

<bean id="expressionHandler" class="org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler">
<property name="permissionEvaluator" ref="permissionEvaluator"/>
</bean>

<bean id="permissionEvaluator" class="com.cjl.security.evaluators.MethodPermissionEvaluator"/>


</beans>

最佳答案

正在发生的事情是抛出 AccessDeniedException,因此您希望配置系统以拦截该异常并返回 JSON。

您可以在您的 Controller 中设置一个@ExceptionHandler 方法来捕获AccessDeniedException。但是,您可能希望在所有 Controller 中做同样的事情,因此如果您使用的是 Spring 3.2,则可以在单独的“建议”类上使用 @ControllerAdvice 注释,然后包含 @ExceptionHandler 方法在那里。

@ControllerAdvice 
public class ExceptionControllerAdvice {

@ExceptionHandler(AccessDeniedException.class)
@ResponseBody
public String exception(AccessDeniedException e) {
return "{\"status\":\"access denied\"}";
}
}

关于java - 使用 Spring Security 'hasPermission()' 在未经授权的 REST 服务请求上返回 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23557942/

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