properties admin = adminRole user1 = userRole user2 = userRole import org.pac4j.core.authorization.authorizer.RequireAnyRoleAuthorizer; import org.pac4j.core.config.Config; import org.pac4j.core.context.HttpConstants; import org.pac4j.core.context.WebContext; import org.pac4j.core.context.session.JEESessionStore; import org.pac4j.core.matching.PathMatcher; import org.pac4j.http.client.direct.BasicAuthClient; import org.pac4j.http.client.indirect.FormClient; import org.pac4j.http.credentials.authenticator.test.SimpleTestUsernamePasswordAuthenticator; import org.pac4j.http.credentials.authenticator.UsernamePasswordAuthenticator; import org.pac4j.http.credentials.authenticator.test.SimpleTestUsernamePasswordAuthenticator; import org.pac4j.jwt.credentials.authenticator.JwtAuthenticator; import org.pac4j.jwt.profile.JwtGenerator; import org.pac4j.jwt.profile.JwtProfile; import org.pac4j.core.profile.CommonProfile; import org.pac4j.core.profile.creator.ProfileCreator; import java.util.Arrays; import java.util.List; import java.util.Properties; public class Main { public static void main(String[] args) { Properties properties = new Properties(); properties.setProperty("pac4j.security.properties", "security.properties"); Config config = new Config(properties); AttributeRoleAuthenticator attributeRoleAuthenticator = new AttributeRoleAuthenticator(); config.getClients().setDefaultSecurityClients(attributeRoleAuthenticator); AttributeMatcher attributeMatcher = new AttributeMatcher(); attributeMatcher.setMatcherName(PathMatcher.MATCH_START); attributeMatcher.setRequiresAny(true); config.addMatcher(HttpConstants.HTTP_METHOD.ALL, "/protected/*", attributeMatcher); RequireAnyRoleAuthorizer requireAdminRole = new RequireAnyRoleAuthorizer("admin"); RequireAnyRoleAuthorizer requireUserRole = new RequireAnyRoleAuthorizer("userRole"); attributeMatcher.getAuthorizers().addAll(Arrays.asList(requireAdminRole, requireUserRole)); List<String> roles = attributeRoleAuthenticator.extractRoles(context); if (roles.contains("admin")) { } else if (roles.contains("userRole")) { } else { } } }


上一篇:
下一篇:
切换中文