gpt4 book ai didi

java - 在哪里可以定义关注某个角色的用户?

转载 作者:行者123 更新时间:2023-11-30 02:48:50 24 4
gpt4 key购买 nike

我正在使用 https://jersey.java.net/documentation/latest/security.html#annotation-based-security 中定义的 RolesAllowedDynamicFeature示例16.5和16.6

我将其注册为:

@ApplicationPath("/demo")
public class App extends ResourceConfig {
public App() {
this.packages("com.bla bla bla package");
register(RolesAllowedDynamicFeature.class);
}
}

然后在 Java 类中我这样做:

@Path("request")
@RolesAllowed({ "admin", "thirdPartyDeveloper" })
public class DemoService {
}

我的问题是在哪里声明属于admin角色的用户和属于第三方开发者角色的用户?

我可以在哪里设置他们的凭据?

最佳答案

这取决于您的身份验证机制。

Java EE 安全性

如果您依赖 servlet 容器提供的标准 Java EE Web 应用程序安全机制,则可以通过应用程序的 web.xml 配置身份验证。描述符。您很可能需要在容器中定义一个领域并在 web.xml 中引用它。描述符为 <real-name>元素。像这样的东西:

<security-constraint>
<web-resource-collection>
<url-pattern>/rest/admin/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>admin</role-name>
</auth-constraint>
</security-constraint>
<security-constraint>
<web-resource-collection>
<url-pattern>/rest/orders/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>customer</role-name>
</auth-constraint>
</security-constraint>
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>my-default-realm</realm-name>
</login-config>

在这种方法中,您的领域将告诉容器用户是否处于某个角色。

要了解有关 Java EE 安全性的更多信息,请查看 Java EE Tutorial .

自定义身份验证

另一方面,当您执行像 this answer 中所述的自定义身份验证时,您可以使用 SecurityContext 的自定义实现。在这种情况下,您需要根据 LDAP、数据库、文件等手动对用户进行身份验证。

对于自定义身份验证,您可以使用 ContainerRequestFilter 如下图所示:

@Provider
@Priority(Priorities.AUTHENTICATION)
public class AuthenticationFilter implements ContainerRequestFilter {

@Override
public void filter(ContainerRequestContext requestContext) throws IOException {

// Authenticate the user: How the authentications will be performed is up to you
// If the authentication failed, abort the request with a 401 status code
// If the authentication succeeded, you know who your user claims to be

final SecurityContext securityContext = requestContext.getSecurityContext();
requestContext.setSecurityContext(new SecurityContext() {

@Override
public Principal getUserPrincipal() {
return new Principal() {
@Override
public String getName() {
// Return the user name here
return null;
}
};
}

@Override
public boolean isUserInRole(String role) {
// Return if the user is in a role
return true;
}

@Override
public boolean isSecure() {
return securityContext.isSecure();
}

@Override
public String getAuthenticationScheme() {
return "Custom";
}
});
}
}

如何执行身份验证是您的事。建议的 HTTP 身份验证方法是在 Authorization 中发送凭据。请求的 header 。 ContainerRequestContext API 将使您能够访问请求的详细信息。

在此方法中,需要编写代码来确定用户是否处于某个角色。

<小时/>

注意:请注意,您不会依赖 session 。每个请求都必须执行身份验证/授权过程。

关于java - 在哪里可以定义关注某个角色的用户?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39330889/

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