repo stringclasses 1k
values | file_url stringlengths 96 373 | file_path stringlengths 11 294 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 6
values | commit_sha stringclasses 1k
values | retrieved_at stringdate 2026-01-04 14:45:56 2026-01-04 18:30:23 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/RefreshTokenServlet.java | security-modules/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/RefreshTokenServlet.java | package com.baeldung.oauth2.client;
import org.eclipse.microprofile.config.Config;
import javax.inject.Inject;
import javax.json.JsonObject;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.IOException;
@WebServlet(urlPatterns = "/refreshtoken")
public class RefreshTokenServlet extends AbstractServlet {
@Inject
private Config config;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String clientId = config.getValue("client.clientId", String.class);
String clientSecret = config.getValue("client.clientSecret", String.class);
JsonObject actualTokenResponse = (JsonObject) request.getSession().getAttribute("tokenResponse");
Client client = ClientBuilder.newClient();
WebTarget target = client.target(config.getValue("provider.tokenUri", String.class));
Form form = new Form();
form.param("grant_type", "refresh_token");
form.param("refresh_token", actualTokenResponse.getString("refresh_token"));
String scope = request.getParameter("scope");
if (scope != null && !scope.isEmpty()) {
form.param("scope", scope);
}
Response jaxrsResponse = target.request(MediaType.APPLICATION_JSON_TYPE)
.header(HttpHeaders.AUTHORIZATION, getAuthorizationHeaderValue(clientId, clientSecret))
.post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE), Response.class);
JsonObject tokenResponse = jaxrsResponse.readEntity(JsonObject.class);
if (jaxrsResponse.getStatus() == 200) {
request.getSession().setAttribute("tokenResponse", tokenResponse);
} else {
request.setAttribute("error", tokenResponse.getString("error_description", "error!"));
}
dispatch("/", request, response);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/DownstreamCallServlet.java | security-modules/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/DownstreamCallServlet.java | package com.baeldung.oauth2.client;
import org.eclipse.microprofile.config.Config;
import javax.inject.Inject;
import javax.json.JsonObject;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.client.*;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet(urlPatterns = "/downstream")
public class DownstreamCallServlet extends HttpServlet {
@Inject
private Config config;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=UTF-8");
String action = request.getParameter("action");
Client client = ClientBuilder.newClient();
WebTarget webTarget = client.target(config.getValue("resourceServerUri", String.class));
WebTarget resourceWebTarget;
String response = null;
JsonObject tokenResponse = (JsonObject) request.getSession().getAttribute("tokenResponse");
if ("read".equals(action)) {
resourceWebTarget = webTarget.path("resource/read");
Invocation.Builder invocationBuilder = resourceWebTarget.request();
response = invocationBuilder
.header("authorization", tokenResponse.getString("access_token"))
.get(String.class);
} else if ("write".equals(action)) {
resourceWebTarget = webTarget.path("resource/write");
Invocation.Builder invocationBuilder = resourceWebTarget.request();
response = invocationBuilder
.header("authorization", tokenResponse.getString("access_token"))
.post(Entity.text("body string"), String.class);
}
PrintWriter out = resp.getWriter();
out.println(response);
out.flush();
out.close();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/AuthorizationCodeServlet.java | security-modules/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/AuthorizationCodeServlet.java | package com.baeldung.oauth2.client;
import org.eclipse.microprofile.config.Config;
import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;
@WebServlet(urlPatterns = "/authorize")
public class AuthorizationCodeServlet extends HttpServlet {
@Inject
private Config config;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//...
request.getSession().removeAttribute("tokenResponse");
String state = UUID.randomUUID().toString();
request.getSession().setAttribute("CLIENT_LOCAL_STATE", state);
String authorizationUri = config.getValue("provider.authorizationUri", String.class);
String clientId = config.getValue("client.clientId", String.class);
String redirectUri = config.getValue("client.redirectUri", String.class);
String scope = config.getValue("client.scope", String.class);
String authorizationLocation = authorizationUri + "?response_type=code"
+ "&client_id=" + clientId
+ "&redirect_uri=" + redirectUri
+ "&scope=" + scope
+ "&state=" + state;
response.sendRedirect(authorizationLocation);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/oauth2-framework-impl/oauth2-resource-server/src/main/java/com/baeldung/oauth2/resource/server/OAuth2ResourceServerApplication.java | security-modules/oauth2-framework-impl/oauth2-resource-server/src/main/java/com/baeldung/oauth2/resource/server/OAuth2ResourceServerApplication.java | package com.baeldung.oauth2.resource.server;
import org.eclipse.microprofile.auth.LoginConfig;
import javax.annotation.security.DeclareRoles;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
@ApplicationPath("/api")
@DeclareRoles({"resource.read", "resource.write"})
@LoginConfig(authMethod = "MP-JWT")
public class OAuth2ResourceServerApplication extends Application {
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/oauth2-framework-impl/oauth2-resource-server/src/main/java/com/baeldung/oauth2/resource/server/secure/ProtectedResource.java | security-modules/oauth2-framework-impl/oauth2-resource-server/src/main/java/com/baeldung/oauth2/resource/server/secure/ProtectedResource.java | package com.baeldung.oauth2.resource.server.secure;
import org.eclipse.microprofile.jwt.JsonWebToken;
import javax.annotation.security.RolesAllowed;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
import java.util.UUID;
@Path("/resource")
@RequestScoped
public class ProtectedResource {
@Inject
private JsonWebToken principal;
@GET
@RolesAllowed("resource.read")
@Path("/read")
public Response read() {
//DoStaff
return Response.ok("Hello, " + principal.getName()).build();
}
@POST
@RolesAllowed("resource.write")
@Path("/write")
public Response write() {
//DoStaff
return Response.ok("Hello, " + principal.getName())
.header("location", UUID.randomUUID().toString())
.build();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/PEMKeyUtils.java | security-modules/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/PEMKeyUtils.java | package com.baeldung.oauth2.authorization.server;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Paths;
import static java.lang.Thread.currentThread;
public class PEMKeyUtils {
public static String readKeyAsString(String keyLocation) throws Exception {
URI uri = currentThread().getContextClassLoader().getResource(keyLocation).toURI();
byte[] byteArray = Files.readAllBytes(Paths.get(uri));
return new String(byteArray);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/OAuth2ServerApplication.java | security-modules/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/OAuth2ServerApplication.java | package com.baeldung.oauth2.authorization.server;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
@ApplicationPath("/")
public class OAuth2ServerApplication extends Application {
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/model/Client.java | security-modules/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/model/Client.java | package com.baeldung.oauth2.authorization.server.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "clients")
public class Client {
@Id
@Column(name = "client_id")
private String clientId;
@Column(name = "client_secret")
private String clientSecret;
@Column(name = "redirect_uri")
private String redirectUri;
@Column(name = "scope")
private String scope;
@Column(name = "authorized_grant_types")
private String authorizedGrantTypes;
public String getClientId() {
return clientId;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
public String getClientSecret() {
return clientSecret;
}
public void setClientSecret(String clientSecret) {
this.clientSecret = clientSecret;
}
public String getRedirectUri() {
return redirectUri;
}
public void setRedirectUri(String redirectUri) {
this.redirectUri = redirectUri;
}
public String getScope() {
return scope;
}
public void setScope(String scope) {
this.scope = scope;
}
public String getAuthorizedGrantTypes() {
return authorizedGrantTypes;
}
public void setAuthorizedGrantTypes(String authorizedGrantTypes) {
this.authorizedGrantTypes = authorizedGrantTypes;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/model/AppDataRepository.java | security-modules/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/model/AppDataRepository.java | package com.baeldung.oauth2.authorization.server.model;
import javax.enterprise.context.ApplicationScoped;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;
@ApplicationScoped
public class AppDataRepository {
@PersistenceContext
private EntityManager entityManager;
public Client getClient(String clientId) {
return entityManager.find(Client.class, clientId);
}
public User getUser(String userId) {
return entityManager.find(User.class, userId);
}
@Transactional
public AuthorizationCode save(AuthorizationCode authorizationCode) {
entityManager.persist(authorizationCode);
return authorizationCode;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/model/User.java | security-modules/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/model/User.java | package com.baeldung.oauth2.authorization.server.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.security.Principal;
@Entity
@Table(name = "users")
public class User implements Principal {
@Id
@Column(name = "user_id")
private String userId;
@Column(name = "password")
private String password;
@Column(name = "roles")
private String roles;
@Column(name = "scopes")
private String scopes;
public String getUserId() {
return userId;
}
public void setUserId(String username) {
this.userId = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRoles() {
return roles;
}
public void setRoles(String roles) {
this.roles = roles;
}
public String getScopes() {
return scopes;
}
public void setScopes(String scopes) {
this.scopes = scopes;
}
@Override
public String getName() {
return getUserId();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/model/AuthorizationCode.java | security-modules/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/model/AuthorizationCode.java | package com.baeldung.oauth2.authorization.server.model;
import javax.persistence.*;
import java.time.LocalDateTime;
@Entity
@Table(name = "authorization_code")
public class AuthorizationCode {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "code")
private String code;
@Column(name = "client_id")
private String clientId;
@Column(name = "user_id")
private String userId;
@Column(name = "approved_scopes")
private String approvedScopes;
@Column(name = "redirect_uri")
private String redirectUri;
@Column(name = "expiration_date")
private LocalDateTime expirationDate;
public String getUserId() {
return userId;
}
public void setUserId(String username) {
this.userId = username;
}
public String getClientId() {
return clientId;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getApprovedScopes() {
return approvedScopes;
}
public void setApprovedScopes(String approvedScopes) {
this.approvedScopes = approvedScopes;
}
public String getRedirectUri() {
return redirectUri;
}
public void setRedirectUri(String redirectUri) {
this.redirectUri = redirectUri;
}
public LocalDateTime getExpirationDate() {
return expirationDate;
}
public void setExpirationDate(LocalDateTime expirationDate) {
this.expirationDate = expirationDate;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/JWKEndpoint.java | security-modules/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/JWKEndpoint.java | package com.baeldung.oauth2.authorization.server.api;
import com.baeldung.oauth2.authorization.server.PEMKeyUtils;
import com.nimbusds.jose.jwk.JWK;
import org.eclipse.microprofile.config.Config;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.Arrays;
@Path("jwk")
@ApplicationScoped
public class JWKEndpoint {
@Inject
private Config config;
@GET
public Response getKey(@QueryParam("format") String format) throws Exception {
if (format != null && !Arrays.asList("jwk", "pem").contains(format)) {
return Response.status(Response.Status.BAD_REQUEST).entity("Public Key Format should be : jwk or pem").build();
}
String verificationkey = config.getValue("verificationkey", String.class);
String pemEncodedRSAPublicKey = PEMKeyUtils.readKeyAsString(verificationkey);
if (format == null || format.equals("jwk")) {
JWK jwk = JWK.parseFromPEMEncodedObjects(pemEncodedRSAPublicKey);
return Response.ok(jwk.toJSONString()).type(MediaType.APPLICATION_JSON).build();
} else if (format.equals("pem")) {
return Response.ok(pemEncodedRSAPublicKey).build();
}
return null;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/AuthorizationEndpoint.java | security-modules/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/AuthorizationEndpoint.java | package com.baeldung.oauth2.authorization.server.api;
import com.baeldung.oauth2.authorization.server.handler.AuthorizationGrantTypeHandler;
import com.baeldung.oauth2.authorization.server.model.AppDataRepository;
import com.baeldung.oauth2.authorization.server.model.AuthorizationCode;
import com.baeldung.oauth2.authorization.server.model.Client;
import com.baeldung.oauth2.authorization.server.model.User;
import javax.annotation.security.RolesAllowed;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.inject.Instance;
import javax.enterprise.inject.literal.NamedLiteral;
import javax.inject.Inject;
import javax.json.JsonObject;
import javax.security.enterprise.SecurityContext;
import javax.security.enterprise.authentication.mechanism.http.FormAuthenticationMechanismDefinition;
import javax.security.enterprise.authentication.mechanism.http.LoginToContinue;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.*;
import javax.ws.rs.core.*;
import java.io.IOException;
import java.net.URI;
import java.security.Principal;
import java.time.LocalDateTime;
import java.util.*;
@FormAuthenticationMechanismDefinition(
loginToContinue = @LoginToContinue(loginPage = "/login.jsp", errorPage = "/login.jsp")
)
@RolesAllowed("USER")
@RequestScoped
@Path("authorize")
public class AuthorizationEndpoint {
@Inject
private SecurityContext securityContext;
@Inject
private AppDataRepository appDataRepository;
@Inject
Instance<AuthorizationGrantTypeHandler> authorizationGrantTypeHandlers;
@GET
@Produces(MediaType.TEXT_HTML)
public Response doGet(@Context HttpServletRequest request,
@Context HttpServletResponse response,
@Context UriInfo uriInfo) throws ServletException, IOException {
MultivaluedMap<String, String> params = uriInfo.getQueryParameters();
Principal principal = securityContext.getCallerPrincipal();
//error about redirect_uri && client_id ==> forward user, thus to error.jsp.
//otherwise ==> sendRedirect redirect_uri?error=error&error_description=error_description
//1. client_id
String clientId = params.getFirst("client_id");
if (clientId == null || clientId.isEmpty()) {
return informUserAboutError(request, response, "Invalid client_id :" + clientId);
}
Client client = appDataRepository.getClient(clientId);
if (client == null) {
return informUserAboutError(request, response, "Invalid client_id :" + clientId);
}
//2. Client Authorized Grant Type
String clientError = "";
if (client.getAuthorizedGrantTypes() != null && !client.getAuthorizedGrantTypes().contains("authorization_code")) {
return informUserAboutError(request, response, "Authorization Grant type, authorization_code, is not allowed for this client :" + clientId);
}
//3. redirectUri
String redirectUri = params.getFirst("redirect_uri");
if (client.getRedirectUri() != null && !client.getRedirectUri().isEmpty()) {
if (redirectUri != null && !redirectUri.isEmpty() && !client.getRedirectUri().equals(redirectUri)) {
//sould be in the client.redirectUri
return informUserAboutError(request, response, "redirect_uri is pre-registred and should match");
}
redirectUri = client.getRedirectUri();
params.putSingle("resolved_redirect_uri", redirectUri);
} else {
if (redirectUri == null || redirectUri.isEmpty()) {
return informUserAboutError(request, response, "redirect_uri is not pre-registred and should be provided");
}
params.putSingle("resolved_redirect_uri", redirectUri);
}
request.setAttribute("client", client);
//4. response_type
String responseType = params.getFirst("response_type");
if (!"code".equals(responseType) && !"token".equals(responseType)) {
//error = "invalid_grant :" + responseType + ", response_type params should be code or token:";
//return informUserAboutError(error);
}
//Save params in session
request.getSession().setAttribute("ORIGINAL_PARAMS", params);
//4.scope: Optional
String requestedScope = request.getParameter("scope");
if (requestedScope == null || requestedScope.isEmpty()) {
requestedScope = client.getScope();
}
User user = appDataRepository.getUser(principal.getName());
String allowedScopes = checkUserScopes(user.getScopes(), requestedScope);
request.setAttribute("scopes", allowedScopes);
request.getRequestDispatcher("/authorize.jsp").forward(request, response);
return null;
}
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.TEXT_HTML)
public Response doPost(@Context HttpServletRequest request,
@Context HttpServletResponse response,
MultivaluedMap<String, String> params) throws Exception {
MultivaluedMap<String, String> originalParams = (MultivaluedMap<String, String>) request.getSession().getAttribute("ORIGINAL_PARAMS");
if (originalParams == null) {
return informUserAboutError(request, response, "No pending authorization request.");
}
String redirectUri = originalParams.getFirst("resolved_redirect_uri");
StringBuilder sb = new StringBuilder(redirectUri);
String approvalStatus = params.getFirst("approval_status");
if ("NO".equals(approvalStatus)) {
URI location = UriBuilder.fromUri(sb.toString())
.queryParam("error", "User doesn't approved the request.")
.queryParam("error_description", "User doesn't approved the request.")
.build();
return Response.seeOther(location).build();
}
//==> YES
List<String> approvedScopes = params.get("scope");
if (approvedScopes == null || approvedScopes.isEmpty()) {
URI location = UriBuilder.fromUri(sb.toString())
.queryParam("error", "User doesn't approved the request.")
.queryParam("error_description", "User doesn't approved the request.")
.build();
return Response.seeOther(location).build();
}
String responseType = originalParams.getFirst("response_type");
String clientId = originalParams.getFirst("client_id");
if ("code".equals(responseType)) {
String userId = securityContext.getCallerPrincipal().getName();
AuthorizationCode authorizationCode = new AuthorizationCode();
authorizationCode.setClientId(clientId);
authorizationCode.setUserId(userId);
authorizationCode.setApprovedScopes(String.join(" ", approvedScopes));
authorizationCode.setExpirationDate(LocalDateTime.now().plusMinutes(10));
authorizationCode.setRedirectUri(redirectUri);
appDataRepository.save(authorizationCode);
String code = authorizationCode.getCode();
sb.append("?code=").append(code);
} else {
//Implicit: responseType=token
AuthorizationGrantTypeHandler authorizationGrantTypeHandler = authorizationGrantTypeHandlers.select(NamedLiteral.of("implicit")).get();
JsonObject tokenResponse = authorizationGrantTypeHandler.createAccessToken(clientId, params);
sb.append("#access_token=").append(tokenResponse.getString("access_token"))
.append("&token_type=").append(tokenResponse.getString("token_type"))
.append("&scope=").append(tokenResponse.getString("scope"));
}
String state = originalParams.getFirst("state");
if (state != null) {
sb.append("&state=").append(state);
}
return Response.seeOther(UriBuilder.fromUri(sb.toString()).build()).build();
}
private String checkUserScopes(String userScopes, String requestedScope) {
Set<String> allowedScopes = new LinkedHashSet<>();
Set<String> rScopes = new HashSet(Arrays.asList(requestedScope.split(" ")));
Set<String> uScopes = new HashSet(Arrays.asList(userScopes.split(" ")));
for (String scope : uScopes) {
if (rScopes.contains(scope)) allowedScopes.add(scope);
}
return String.join(" ", allowedScopes);
}
private Response informUserAboutError(HttpServletRequest request, HttpServletResponse response, String error) throws ServletException, IOException {
request.setAttribute("error", error);
request.getRequestDispatcher("/error.jsp").forward(request, response);
return null;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/TokenEndpoint.java | security-modules/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/TokenEndpoint.java | package com.baeldung.oauth2.authorization.server.api;
import com.baeldung.oauth2.authorization.server.handler.AuthorizationGrantTypeHandler;
import com.baeldung.oauth2.authorization.server.model.AppDataRepository;
import com.baeldung.oauth2.authorization.server.model.Client;
import com.nimbusds.jose.JOSEException;
import javax.enterprise.inject.Instance;
import javax.enterprise.inject.literal.NamedLiteral;
import javax.inject.Inject;
import javax.json.Json;
import javax.json.JsonObject;
import javax.ws.rs.*;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;
@Path("token")
public class TokenEndpoint {
List<String> supportedGrantTypes = Arrays.asList("authorization_code", "refresh_token");
@Inject
private AppDataRepository appDataRepository;
@Inject
Instance<AuthorizationGrantTypeHandler> authorizationGrantTypeHandlers;
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response token(MultivaluedMap<String, String> params,
@HeaderParam(HttpHeaders.AUTHORIZATION) String authHeader) throws JOSEException {
//Check grant_type params
String grantType = params.getFirst("grant_type");
if (grantType == null || grantType.isEmpty())
return responseError("Invalid_request", "grant_type is required", Response.Status.BAD_REQUEST);
if (!supportedGrantTypes.contains(grantType)) {
return responseError("unsupported_grant_type", "grant_type should be one of :" + supportedGrantTypes, Response.Status.BAD_REQUEST);
}
//Client Authentication
String[] clientCredentials = extract(authHeader);
if (clientCredentials.length != 2) {
return responseError("Invalid_request", "Bad Credentials client_id/client_secret", Response.Status.BAD_REQUEST);
}
String clientId = clientCredentials[0];
Client client = appDataRepository.getClient(clientId);
if (client == null) {
return responseError("Invalid_request", "Invalid client_id", Response.Status.BAD_REQUEST);
}
String clientSecret = clientCredentials[1];
if (!clientSecret.equals(client.getClientSecret())) {
return responseError("Invalid_request", "Invalid client_secret", Response.Status.UNAUTHORIZED);
}
AuthorizationGrantTypeHandler authorizationGrantTypeHandler = authorizationGrantTypeHandlers.select(NamedLiteral.of(grantType)).get();
JsonObject tokenResponse = null;
try {
tokenResponse = authorizationGrantTypeHandler.createAccessToken(clientId, params);
} catch (WebApplicationException e) {
return e.getResponse();
} catch (Exception e) {
return responseError("Invalid_request", "Can't get token", Response.Status.INTERNAL_SERVER_ERROR);
}
return Response.ok(tokenResponse)
.header("Cache-Control", "no-store")
.header("Pragma", "no-cache")
.build();
}
private String[] extract(String authHeader) {
if (authHeader != null && authHeader.startsWith("Basic ")) {
return new String(Base64.getDecoder().decode(authHeader.substring(6))).split(":");
}
return new String[]{};
}
private Response responseError(String error, String errorDescription, Response.Status status) {
JsonObject errorResponse = Json.createObjectBuilder()
.add("error", error)
.add("error_description", errorDescription)
.build();
return Response.status(status)
.entity(errorResponse).build();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/security/UserIdentityStore.java | security-modules/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/security/UserIdentityStore.java | package com.baeldung.oauth2.authorization.server.security;
import com.baeldung.oauth2.authorization.server.model.AppDataRepository;
import com.baeldung.oauth2.authorization.server.model.User;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.security.enterprise.credential.Credential;
import javax.security.enterprise.credential.UsernamePasswordCredential;
import javax.security.enterprise.identitystore.CredentialValidationResult;
import javax.security.enterprise.identitystore.IdentityStore;
import javax.transaction.Transactional;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Objects;
import static javax.security.enterprise.identitystore.CredentialValidationResult.INVALID_RESULT;
@ApplicationScoped
@Transactional
public class UserIdentityStore implements IdentityStore {
@Inject
private AppDataRepository appDataRepository;
@Override
public CredentialValidationResult validate(Credential credential) {
UsernamePasswordCredential usernamePasswordCredential = (UsernamePasswordCredential) credential;
String userId = usernamePasswordCredential.getCaller();
User user = appDataRepository.getUser(userId);
Objects.requireNonNull(user, "User should be not null");
if (usernamePasswordCredential.getPasswordAsString().equals(user.getPassword())) {
return new CredentialValidationResult(userId, new HashSet<>(Arrays.asList(user.getRoles().split(","))));
}
return INVALID_RESULT;
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/RefreshTokenGrantTypeHandler.java | security-modules/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/RefreshTokenGrantTypeHandler.java | package com.baeldung.oauth2.authorization.server.handler;
import com.nimbusds.jose.JWSVerifier;
import com.nimbusds.jwt.SignedJWT;
import javax.inject.Named;
import javax.json.Json;
import javax.json.JsonObject;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
@Named("refresh_token")
public class RefreshTokenGrantTypeHandler extends AbstractGrantTypeHandler {
@Override
public JsonObject createAccessToken(String clientId, MultivaluedMap<String, String> params) throws Exception {
String refreshToken = params.getFirst("refresh_token");
if (refreshToken == null || "".equals(refreshToken)) {
throw new WebApplicationException("invalid_grant");
}
//Decode refresh token
SignedJWT signedRefreshToken = SignedJWT.parse(refreshToken);
JWSVerifier verifier = getJWSVerifier();
if (!signedRefreshToken.verify(verifier)) {
throw new WebApplicationException("Invalid refresh token.");
}
if (!(new Date().before(signedRefreshToken.getJWTClaimsSet().getExpirationTime()))) {
throw new WebApplicationException("Refresh token expired.");
}
String refreshTokenClientId = signedRefreshToken.getJWTClaimsSet().getStringClaim("client_id");
if (!clientId.equals(refreshTokenClientId)) {
throw new WebApplicationException("Invalid client_id.");
}
//At this point, the refresh token is valid and not yet expired
//So create a new access token from it.
String subject = signedRefreshToken.getJWTClaimsSet().getSubject();
String approvedScopes = signedRefreshToken.getJWTClaimsSet().getStringClaim("scope");
String requestedScopes = params.getFirst("scope");
if (requestedScopes != null && !requestedScopes.isEmpty()) {
Set<String> rScopes = new HashSet(Arrays.asList(requestedScopes.split(" ")));
Set<String> aScopes = new HashSet(Arrays.asList(approvedScopes.split(" ")));
if (!aScopes.containsAll(rScopes)) {
JsonObject error = Json.createObjectBuilder()
.add("error", "Invalid_request")
.add("error_description", "Requested scopes should be a subset of the original scopes.")
.build();
Response response = Response.status(Response.Status.BAD_REQUEST).entity(error).build();
throw new WebApplicationException(response);
}
} else {
requestedScopes = approvedScopes;
}
String accessToken = getAccessToken(clientId, subject, requestedScopes);
return Json.createObjectBuilder()
.add("token_type", "Bearer")
.add("access_token", accessToken)
.add("expires_in", expiresInMin * 60)
.add("scope", requestedScopes)
.add("refresh_token", refreshToken)
.build();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/AuthorizationGrantTypeHandler.java | security-modules/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/AuthorizationGrantTypeHandler.java | package com.baeldung.oauth2.authorization.server.handler;
import javax.json.JsonObject;
import javax.ws.rs.core.MultivaluedMap;
public interface AuthorizationGrantTypeHandler {
JsonObject createAccessToken(String clientId, MultivaluedMap<String, String> params) throws Exception;
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/AuthorizationCodeGrantTypeHandler.java | security-modules/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/AuthorizationCodeGrantTypeHandler.java | package com.baeldung.oauth2.authorization.server.handler;
import com.baeldung.oauth2.authorization.server.model.AuthorizationCode;
import javax.inject.Named;
import javax.json.Json;
import javax.json.JsonObject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MultivaluedMap;
import java.time.LocalDateTime;
@Named("authorization_code")
public class AuthorizationCodeGrantTypeHandler extends AbstractGrantTypeHandler {
@PersistenceContext
private EntityManager entityManager;
@Override
public JsonObject createAccessToken(String clientId, MultivaluedMap<String, String> params) throws Exception {
//1. code is required
String code = params.getFirst("code");
if (code == null || "".equals(code)) {
throw new WebApplicationException("invalid_grant");
}
AuthorizationCode authorizationCode = entityManager.find(AuthorizationCode.class, code);
if (!authorizationCode.getExpirationDate().isAfter(LocalDateTime.now())) {
throw new WebApplicationException("code Expired !");
}
String redirectUri = params.getFirst("redirect_uri");
//redirecturi match
if (authorizationCode.getRedirectUri() != null && !authorizationCode.getRedirectUri().equals(redirectUri)) {
//redirectUri params should be the same as the requested redirectUri.
throw new WebApplicationException("invalid_grant");
}
//client match
if (!clientId.equals(authorizationCode.getClientId())) {
throw new WebApplicationException("invalid_grant");
}
//3. JWT Payload or claims
String accessToken = getAccessToken(clientId, authorizationCode.getUserId(), authorizationCode.getApprovedScopes());
String refreshToken = getRefreshToken(clientId, authorizationCode.getUserId(), authorizationCode.getApprovedScopes());
return Json.createObjectBuilder()
.add("token_type", "Bearer")
.add("access_token", accessToken)
.add("expires_in", expiresInMin * 60)
.add("scope", authorizationCode.getApprovedScopes())
.add("refresh_token", refreshToken)
.build();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/AbstractGrantTypeHandler.java | security-modules/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/AbstractGrantTypeHandler.java | package com.baeldung.oauth2.authorization.server.handler;
import com.baeldung.oauth2.authorization.server.PEMKeyUtils;
import com.nimbusds.jose.*;
import com.nimbusds.jose.crypto.RSASSASigner;
import com.nimbusds.jose.crypto.RSASSAVerifier;
import com.nimbusds.jose.jwk.JWK;
import com.nimbusds.jose.jwk.RSAKey;
import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.SignedJWT;
import org.eclipse.microprofile.config.Config;
import javax.inject.Inject;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.Date;
import java.util.UUID;
public abstract class AbstractGrantTypeHandler implements AuthorizationGrantTypeHandler {
//Always RSA 256, but could be parametrized
protected JWSHeader jwsHeader = new JWSHeader.Builder(JWSAlgorithm.RS256).type(JOSEObjectType.JWT).build();
@Inject
protected Config config;
//30 min
protected Long expiresInMin = 30L;
protected JWSVerifier getJWSVerifier() throws Exception {
String verificationkey = config.getValue("verificationkey", String.class);
String pemEncodedRSAPublicKey = PEMKeyUtils.readKeyAsString(verificationkey);
RSAKey rsaPublicKey = (RSAKey) JWK.parseFromPEMEncodedObjects(pemEncodedRSAPublicKey);
return new RSASSAVerifier(rsaPublicKey);
}
protected JWSSigner getJwsSigner() throws Exception {
String signingkey = config.getValue("signingkey", String.class);
String pemEncodedRSAPrivateKey = PEMKeyUtils.readKeyAsString(signingkey);
RSAKey rsaKey = (RSAKey) JWK.parseFromPEMEncodedObjects(pemEncodedRSAPrivateKey);
return new RSASSASigner(rsaKey.toRSAPrivateKey());
}
protected String getAccessToken(String clientId, String subject, String approvedScope) throws Exception {
//4. Signing
JWSSigner jwsSigner = getJwsSigner();
Instant now = Instant.now();
//Long expiresInMin = 30L;
Date expirationTime = Date.from(now.plus(expiresInMin, ChronoUnit.MINUTES));
//3. JWT Payload or claims
JWTClaimsSet jwtClaims = new JWTClaimsSet.Builder()
.issuer("http://localhost:9080")
.subject(subject)
.claim("upn", subject)
.claim("client_id", clientId)
.audience("http://localhost:9280")
.claim("scope", approvedScope)
.claim("groups", Arrays.asList(approvedScope.split(" ")))
.expirationTime(expirationTime) // expires in 30 minutes
.notBeforeTime(Date.from(now))
.issueTime(Date.from(now))
.jwtID(UUID.randomUUID().toString())
.build();
SignedJWT signedJWT = new SignedJWT(jwsHeader, jwtClaims);
signedJWT.sign(jwsSigner);
return signedJWT.serialize();
}
protected String getRefreshToken(String clientId, String subject, String approvedScope) throws Exception {
JWSSigner jwsSigner = getJwsSigner();
Instant now = Instant.now();
//6.Build refresh token
JWTClaimsSet refreshTokenClaims = new JWTClaimsSet.Builder()
.subject(subject)
.claim("client_id", clientId)
.claim("scope", approvedScope)
//refresh token for 1 day.
.expirationTime(Date.from(now.plus(1, ChronoUnit.DAYS)))
.build();
SignedJWT signedRefreshToken = new SignedJWT(jwsHeader, refreshTokenClaims);
signedRefreshToken.sign(jwsSigner);
return signedRefreshToken.serialize();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/cloud-foundry-uaa/cf-uaa-oauth2-client/src/main/java/com/baeldung/cfuaa/oauth2/client/CFUAAOAuth2ClientApplication.java | security-modules/cloud-foundry-uaa/cf-uaa-oauth2-client/src/main/java/com/baeldung/cfuaa/oauth2/client/CFUAAOAuth2ClientApplication.java | package com.baeldung.cfuaa.oauth2.client;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class CFUAAOAuth2ClientApplication {
public static void main(String[] args) {
SpringApplication.run(CFUAAOAuth2ClientApplication.class, args);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/cloud-foundry-uaa/cf-uaa-oauth2-client/src/main/java/com/baeldung/cfuaa/oauth2/client/CFUAAOAuth2ClientController.java | security-modules/cloud-foundry-uaa/cf-uaa-oauth2-client/src/main/java/com/baeldung/cfuaa/oauth2/client/CFUAAOAuth2ClientController.java | package com.baeldung.cfuaa.oauth2.client;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;
@RestController
public class CFUAAOAuth2ClientController {
@Value("${resource.server.url}")
private String remoteResourceServer;
private RestTemplate restTemplate;
private OAuth2AuthorizedClientService authorizedClientService;
public CFUAAOAuth2ClientController(OAuth2AuthorizedClientService authorizedClientService) {
this.authorizedClientService = authorizedClientService;
this.restTemplate = new RestTemplate();
}
@RequestMapping("/")
public String index(OAuth2AuthenticationToken authenticationToken) {
OAuth2AuthorizedClient oAuth2AuthorizedClient = this.authorizedClientService.loadAuthorizedClient(authenticationToken.getAuthorizedClientRegistrationId(), authenticationToken.getName());
OAuth2AccessToken oAuth2AccessToken = oAuth2AuthorizedClient.getAccessToken();
String response = "Hello, " + authenticationToken.getPrincipal().getName();
response += "</br></br>";
response += "Here is your accees token :</br>" + oAuth2AccessToken.getTokenValue();
response += "</br>";
response += "</br>You can use it to call these Resource Server APIs:";
response += "</br></br>";
response += "<a href='/read'>Call Resource Server Read API</a>";
response += "</br>";
response += "<a href='/write'>Call Resource Server Write API</a>";
return response;
}
@RequestMapping("/read")
public String read(OAuth2AuthenticationToken authenticationToken) {
String url = remoteResourceServer + "/read";
return callResourceServer(authenticationToken, url);
}
@RequestMapping("/write")
public String write(OAuth2AuthenticationToken authenticationToken) {
String url = remoteResourceServer + "/write";
return callResourceServer(authenticationToken, url);
}
private String callResourceServer(OAuth2AuthenticationToken authenticationToken, String url) {
OAuth2AuthorizedClient oAuth2AuthorizedClient = this.authorizedClientService.loadAuthorizedClient(authenticationToken.getAuthorizedClientRegistrationId(), authenticationToken.getName());
OAuth2AccessToken oAuth2AccessToken = oAuth2AuthorizedClient.getAccessToken();
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Bearer " + oAuth2AccessToken.getTokenValue());
HttpEntity<String> entity = new HttpEntity<>("parameters", headers);
ResponseEntity<String> responseEntity = null;
String response = null;
try {
responseEntity = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
response = responseEntity.getBody();
} catch (HttpClientErrorException e) {
response = e.getMessage();
}
return response;
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/cloud-foundry-uaa/cf-uaa-oauth2-resource-server/src/main/java/com/baeldung/cfuaa/oauth2/resourceserver/CFUAAOAuth2ResourceServerApplication.java | security-modules/cloud-foundry-uaa/cf-uaa-oauth2-resource-server/src/main/java/com/baeldung/cfuaa/oauth2/resourceserver/CFUAAOAuth2ResourceServerApplication.java | package com.baeldung.cfuaa.oauth2.resourceserver;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class CFUAAOAuth2ResourceServerApplication {
public static void main(String[] args) {
SpringApplication.run(CFUAAOAuth2ResourceServerApplication.class, args);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/cloud-foundry-uaa/cf-uaa-oauth2-resource-server/src/main/java/com/baeldung/cfuaa/oauth2/resourceserver/CFUAAOAuth2ResourceServerRestController.java | security-modules/cloud-foundry-uaa/cf-uaa-oauth2-resource-server/src/main/java/com/baeldung/cfuaa/oauth2/resourceserver/CFUAAOAuth2ResourceServerRestController.java | package com.baeldung.cfuaa.oauth2.resourceserver;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.security.Principal;
@RestController
public class CFUAAOAuth2ResourceServerRestController {
@GetMapping("/")
public String index(@AuthenticationPrincipal Jwt jwt) {
return String.format("Hello, %s!", jwt.getSubject());
}
@GetMapping("/read")
public String read(JwtAuthenticationToken jwtAuthenticationToken) {
return "Hello read: " + jwtAuthenticationToken.getTokenAttributes();
}
@GetMapping("/write")
public String write(Principal principal) {
return "Hello write: " + principal.getName();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/cloud-foundry-uaa/cf-uaa-oauth2-resource-server/src/main/java/com/baeldung/cfuaa/oauth2/resourceserver/CFUAAOAuth2ResourceServerSecurityConfiguration.java | security-modules/cloud-foundry-uaa/cf-uaa-oauth2-resource-server/src/main/java/com/baeldung/cfuaa/oauth2/resourceserver/CFUAAOAuth2ResourceServerSecurityConfiguration.java | package com.baeldung.cfuaa.oauth2.resourceserver;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
@EnableWebSecurity
public class CFUAAOAuth2ResourceServerSecurityConfiguration {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(auth -> auth
.requestMatchers("/read/**")
.hasAuthority("SCOPE_resource.read")
.requestMatchers("/write/**")
.hasAuthority("SCOPE_resource.write")
.anyRequest()
.authenticated())
.oauth2ResourceServer((oauth2) -> oauth2.jwt(Customizer.withDefaults()));
return http.build();
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/jee-7-security/src/main/java/com/baeldung/springsecurity/SpringSecurityConfig.java | security-modules/jee-7-security/src/main/java/com/baeldung/springsecurity/SpringSecurityConfig.java | package com.baeldung.springsecurity;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
public class SpringSecurityConfig {
@Bean
public InMemoryUserDetailsManager userDetailsService() {
UserDetails user = User.withUsername("user1")
.password("{noop}user1Pass")
.roles("USER")
.build();
UserDetails admin = User.withUsername("admin")
.password("{noop}adminPass")
.roles("ADMIN")
.build();
return new InMemoryUserDetailsManager(user, admin);
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.csrf()
.disable()
.authorizeRequests()
.antMatchers("/auth/login*")
.anonymous()
.antMatchers("/home/admin*")
.hasRole("ADMIN")
.anyRequest()
.authenticated()
.and()
.formLogin()
.loginPage("/auth/login")
.defaultSuccessUrl("/home", true)
.failureUrl("/auth/login?error=true")
.and()
.logout()
.logoutSuccessUrl("/auth/login");
return http.build();
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/jee-7-security/src/main/java/com/baeldung/springsecurity/SecurityWebApplicationInitializer.java | security-modules/jee-7-security/src/main/java/com/baeldung/springsecurity/SecurityWebApplicationInitializer.java | package com.baeldung.springsecurity;
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
public SecurityWebApplicationInitializer() {
super(SpringSecurityConfig.class);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/jee-7-security/src/main/java/com/baeldung/springsecurity/controller/LoginController.java | security-modules/jee-7-security/src/main/java/com/baeldung/springsecurity/controller/LoginController.java | package com.baeldung.springsecurity.controller;
import javax.mvc.annotation.Controller;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
@Path("/auth/login")
@Controller
public class LoginController {
@GET
public String login() {
return "login.jsp";
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/jee-7-security/src/main/java/com/baeldung/springsecurity/controller/HomeController.java | security-modules/jee-7-security/src/main/java/com/baeldung/springsecurity/controller/HomeController.java | package com.baeldung.springsecurity.controller;
import javax.mvc.annotation.Controller;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
@Path("/home")
@Controller
public class HomeController {
@GET
public String home() {
return "home.jsp";
}
@GET
@Path("/user")
public String admin() {
return "user.jsp";
}
@GET
@Path("/admin")
public String user() {
return "admin.jsp";
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/sql-injection-samples/src/test/java/com/baeldung/examples/security/sql/SqlInjectionSamplesApplicationUnitTest.java | security-modules/sql-injection-samples/src/test/java/com/baeldung/examples/security/sql/SqlInjectionSamplesApplicationUnitTest.java | package com.baeldung.examples.security.sql;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.examples.security.sql.AccountDAO;
import com.baeldung.examples.security.sql.AccountDTO;
@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles({ "test" })
public class SqlInjectionSamplesApplicationUnitTest {
@Autowired
private AccountDAO target;
@Test
public void givenAVulnerableMethod_whenValidCustomerId_thenReturnSingleAccount() {
List<AccountDTO> accounts = target.unsafeFindAccountsByCustomerId("C1");
assertThat(accounts).isNotNull();
assertThat(accounts).isNotEmpty();
assertThat(accounts).hasSize(1);
}
@Test
public void givenAVulnerableMethod_whenHackedCustomerId_thenReturnAllAccounts() {
List<AccountDTO> accounts = target.unsafeFindAccountsByCustomerId("C1' or '1'='1");
assertThat(accounts).isNotNull();
assertThat(accounts).isNotEmpty();
assertThat(accounts).hasSize(3);
}
@Test
public void givenAVulnerableJpaMethod_whenHackedCustomerId_thenReturnAllAccounts() {
List<AccountDTO> accounts = target.unsafeJpaFindAccountsByCustomerId("C1' or '1'='1");
assertThat(accounts).isNotNull();
assertThat(accounts).isNotEmpty();
assertThat(accounts).hasSize(3);
}
@Test
public void givenASafeMethod_whenHackedCustomerId_thenReturnNoAccounts() {
List<AccountDTO> accounts = target.safeFindAccountsByCustomerId("C1' or '1'='1");
assertThat(accounts).isNotNull();
assertThat(accounts).isEmpty();
}
@Test
public void givenASafeJpaMethod_whenHackedCustomerId_thenReturnNoAccounts() {
List<AccountDTO> accounts = target.safeJpaFindAccountsByCustomerId("C1' or '1'='1");
assertThat(accounts).isNotNull();
assertThat(accounts).isEmpty();
}
@Test
public void givenASafeJpaCriteriaMethod_whenHackedCustomerId_thenReturnNoAccounts() {
List<AccountDTO> accounts = target.safeJpaCriteriaFindAccountsByCustomerId("C1' or '1'='1");
assertThat(accounts).isNotNull();
assertThat(accounts).isEmpty();
}
@Test(expected = IllegalArgumentException.class)
public void givenASafeMethod_whenInvalidOrderBy_thenThrowException() {
target.safeFindAccountsByCustomerId("C1", "INVALID");
}
@Test(expected = Exception.class)
public void givenWrongPlaceholderUsageMethod_whenNormalCall_thenThrowsException() {
target.wrongCountRecordsByTableName("Accounts");
}
@Test(expected = Exception.class)
public void givenWrongJpaPlaceholderUsageMethod_whenNormalCall_thenThrowsException() {
target.wrongJpaCountRecordsByTableName("Accounts");
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/Account.java | security-modules/sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/Account.java | /**
*
*/
package com.baeldung.examples.security.sql;
import java.math.BigDecimal;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import lombok.Data;
/**
* @author Philippe
*
*/
@Entity
@Table(name="Accounts")
@Data
public class Account {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
private String customerId;
private String accNumber;
private String branchId;
private BigDecimal balance;
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/AccountDTO.java | security-modules/sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/AccountDTO.java | package com.baeldung.examples.security.sql;
import java.math.BigDecimal;
import lombok.Builder;
import lombok.Data;
@Data
@Builder
public class AccountDTO {
private String customerId;
private String accNumber;
private String branchId;
private BigDecimal balance;
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/AccountDAO.java | security-modules/sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/AccountDAO.java | /**
*
*/
package com.baeldung.examples.security.sql;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.sql.DataSource;
import org.springframework.stereotype.Component;
import jakarta.persistence.EntityManager;
import jakarta.persistence.TypedQuery;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Root;
import jakarta.persistence.metamodel.SingularAttribute;
/**
* @author Philippe
*
*/
@Component
public class AccountDAO {
private final DataSource dataSource;
private final EntityManager em;
public AccountDAO(DataSource dataSource, EntityManager em) {
this.dataSource = dataSource;
this.em = em;
}
/**
* Return all accounts owned by a given customer,given his/her external id
*
* @param customerId
* @return
*/
public List<AccountDTO> unsafeFindAccountsByCustomerId(String customerId) {
String sql = "select " + "customer_id,acc_number,branch_id,balance from Accounts where customer_id = '" + customerId + "'";
try (Connection c = dataSource.getConnection();
ResultSet rs = c.createStatement()
.executeQuery(sql)) {
List<AccountDTO> accounts = new ArrayList<>();
while (rs.next()) {
AccountDTO acc = AccountDTO.builder()
.customerId(rs.getString("customer_id"))
.branchId(rs.getString("branch_id"))
.accNumber(rs.getString("acc_number"))
.balance(rs.getBigDecimal("balance"))
.build();
accounts.add(acc);
}
return accounts;
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
}
/**
* Return all accounts owned by a given customer,given his/her external id - JPA version
*
* @param customerId
* @return
*/
public List<AccountDTO> unsafeJpaFindAccountsByCustomerId(String customerId) {
String jql = "from Account where customerId = '" + customerId + "'";
TypedQuery<Account> q = em.createQuery(jql, Account.class);
return q.getResultList()
.stream()
.map(a -> AccountDTO.builder()
.accNumber(a.getAccNumber())
.balance(a.getBalance())
.branchId(a.getAccNumber())
.customerId(a.getCustomerId())
.build())
.collect(Collectors.toList());
}
/**
* Return all accounts owned by a given customer,given his/her external id
*
* @param customerId
* @return
*/
public List<AccountDTO> safeFindAccountsByCustomerId(String customerId) {
String sql = "select customer_id, branch_id,acc_number,balance from Accounts where customer_id = ?";
try (Connection c = dataSource.getConnection(); PreparedStatement p = c.prepareStatement(sql)) {
p.setString(1, customerId);
ResultSet rs = p.executeQuery();
List<AccountDTO> accounts = new ArrayList<>();
while (rs.next()) {
AccountDTO acc = AccountDTO.builder()
.customerId(rs.getString("customerId"))
.branchId(rs.getString("branch_id"))
.accNumber(rs.getString("acc_number"))
.balance(rs.getBigDecimal("balance"))
.build();
accounts.add(acc);
}
return accounts;
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
}
/**
* Return all accounts owned by a given customer,given his/her external id - JPA version
*
* @param customerId
* @return
*/
public List<AccountDTO> safeJpaFindAccountsByCustomerId(String customerId) {
String jql = "from Account where customerId = :customerId";
TypedQuery<Account> q = em.createQuery(jql, Account.class)
.setParameter("customerId", customerId);
return q.getResultList()
.stream()
.map(a -> AccountDTO.builder()
.accNumber(a.getAccNumber())
.balance(a.getBalance())
.branchId(a.getAccNumber())
.customerId(a.getCustomerId())
.build())
.collect(Collectors.toList());
}
/**
* Return all accounts owned by a given customer,given his/her external id - JPA version
*
* @param customerId
* @return
*/
public List<AccountDTO> safeJpaCriteriaFindAccountsByCustomerId(String customerId) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Account> cq = cb.createQuery(Account.class);
Root<Account> root = cq.from(Account.class);
cq.select(root)
.where(cb.equal(root.get(Account_.customerId), customerId));
TypedQuery<Account> q = em.createQuery(cq);
return q.getResultList()
.stream()
.map(a -> AccountDTO.builder()
.accNumber(a.getAccNumber())
.balance(a.getBalance())
.branchId(a.getAccNumber())
.customerId(a.getCustomerId())
.build())
.collect(Collectors.toList());
}
private static final Set<String> VALID_COLUMNS_FOR_ORDER_BY = Stream.of("acc_number", "branch_id", "balance")
.collect(Collectors.toCollection(HashSet::new));
/**
* Return all accounts owned by a given customer,given his/her external id
*
* @param customerId
* @return
*/
public List<AccountDTO> safeFindAccountsByCustomerId(String customerId, String orderBy) {
String sql = "select " + "customer_id,acc_number,branch_id,balance from Accounts where customer_id = ? ";
if (VALID_COLUMNS_FOR_ORDER_BY.contains(orderBy)) {
sql = sql + " order by " + orderBy;
} else {
throw new IllegalArgumentException("Nice try!");
}
try (Connection c = dataSource.getConnection(); PreparedStatement p = c.prepareStatement(sql)) {
p.setString(1, customerId);
ResultSet rs = p.executeQuery();
List<AccountDTO> accounts = new ArrayList<>();
while (rs.next()) {
AccountDTO acc = AccountDTO.builder()
.customerId(rs.getString("customerId"))
.branchId(rs.getString("branch_id"))
.accNumber(rs.getString("acc_number"))
.balance(rs.getBigDecimal("balance"))
.build();
accounts.add(acc);
}
return accounts;
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
}
private static final Map<String,SingularAttribute<Account,?>> VALID_JPA_COLUMNS_FOR_ORDER_BY = Stream.of(
new AbstractMap.SimpleEntry<>(Account_.ACC_NUMBER, Account_.accNumber),
new AbstractMap.SimpleEntry<>(Account_.BRANCH_ID, Account_.branchId),
new AbstractMap.SimpleEntry<>(Account_.BALANCE, Account_.balance)
)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
/**
* Return all accounts owned by a given customer,given his/her external id
*
* @param customerId
* @return
*/
public List<AccountDTO> safeJpaFindAccountsByCustomerId(String customerId, String orderBy) {
SingularAttribute<Account,?> orderByAttribute = VALID_JPA_COLUMNS_FOR_ORDER_BY.get(orderBy);
if ( orderByAttribute == null) {
throw new IllegalArgumentException("Nice try!");
}
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Account> cq = cb.createQuery(Account.class);
Root<Account> root = cq.from(Account.class);
cq.select(root)
.where(cb.equal(root.get(Account_.customerId), customerId))
.orderBy(cb.asc(root.get(orderByAttribute)));
TypedQuery<Account> q = em.createQuery(cq);
return q.getResultList()
.stream()
.map(a -> AccountDTO.builder()
.accNumber(a.getAccNumber())
.balance(a.getBalance())
.branchId(a.getAccNumber())
.customerId(a.getCustomerId())
.build())
.collect(Collectors.toList());
}
/**
* Invalid placeholder usage example
*
* @param tableName
* @return
*/
public Long wrongCountRecordsByTableName(String tableName) {
try (Connection c = dataSource.getConnection(); PreparedStatement p = c.prepareStatement("select count(*) from ?")) {
p.setString(1, tableName);
ResultSet rs = p.executeQuery();
rs.next();
return rs.getLong(1);
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
}
/**
* Invalid placeholder usage example - JPA
*
* @param tableName
* @return
*/
public Long wrongJpaCountRecordsByTableName(String tableName) {
String jql = "select count(*) from :tableName";
TypedQuery<Long> q = em.createQuery(jql, Long.class)
.setParameter("tableName", tableName);
return q.getSingleResult();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/SqlInjectionSamplesApplication.java | security-modules/sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/SqlInjectionSamplesApplication.java | package com.baeldung.examples.security.sql;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SqlInjectionSamplesApplication {
public static void main(String[] args) {
SpringApplication.run(SqlInjectionSamplesApplication.class, args);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/cas/cas-secured-app/src/test/java/com/baeldung/cassecuredapp/CasSecuredApplicationIntegrationTest.java | security-modules/cas/cas-secured-app/src/test/java/com/baeldung/cassecuredapp/CasSecuredApplicationIntegrationTest.java | package com.baeldung.cassecuredapp;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class CasSecuredApplicationIntegrationTest {
@Test
public void contextLoads() {
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/CasSecuredApplication.java | security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/CasSecuredApplication.java | package com.baeldung.cassecuredapp;
import org.jasig.cas.client.session.SingleSignOutFilter;
import org.jasig.cas.client.validation.Cas30ServiceTicketValidator;
import org.jasig.cas.client.validation.TicketValidator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.cas.ServiceProperties;
import org.springframework.security.cas.authentication.CasAuthenticationProvider;
import org.springframework.security.cas.web.CasAuthenticationFilter;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.logout.LogoutFilter;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import com.baeldung.cassecuredapp.service.CasUserDetailsService;
@SpringBootApplication
public class CasSecuredApplication {
private static final Logger logger = LoggerFactory.getLogger(CasSecuredApplication.class);
public static void main(String... args) {
SpringApplication.run(CasSecuredApplication.class, args);
}
@Bean
public CasAuthenticationFilter casAuthenticationFilter(
AuthenticationManager authenticationManager,
ServiceProperties serviceProperties) throws Exception {
CasAuthenticationFilter filter = new CasAuthenticationFilter();
filter.setAuthenticationManager(authenticationManager);
filter.setServiceProperties(serviceProperties);
return filter;
}
@Bean
public ServiceProperties serviceProperties() {
logger.info("service properties");
ServiceProperties serviceProperties = new ServiceProperties();
serviceProperties.setService("http://localhost:8900/login/cas");
serviceProperties.setSendRenew(false);
return serviceProperties;
}
@Bean
public TicketValidator ticketValidator() {
return new Cas30ServiceTicketValidator("https://localhost:8443/cas");
}
@Bean
public CasUserDetailsService getUser(){
return new CasUserDetailsService();
}
@Bean
public CasAuthenticationProvider casAuthenticationProvider(
TicketValidator ticketValidator,
ServiceProperties serviceProperties) {
CasAuthenticationProvider provider = new CasAuthenticationProvider();
provider.setServiceProperties(serviceProperties);
provider.setTicketValidator(ticketValidator);
provider.setUserDetailsService(
s -> new User("casuser", "Mellon", true, true, true, true,
AuthorityUtils.createAuthorityList("ROLE_ADMIN")));
//For Authentication with a Database-backed UserDetailsService
//provider.setUserDetailsService(getUser());
provider.setKey("CAS_PROVIDER_LOCALHOST_8900");
return provider;
}
@Bean
public SecurityContextLogoutHandler securityContextLogoutHandler() {
return new SecurityContextLogoutHandler();
}
@Bean
public LogoutFilter logoutFilter() {
LogoutFilter logoutFilter = new LogoutFilter("https://localhost:8443/cas/logout", securityContextLogoutHandler());
logoutFilter.setFilterProcessesUrl("/logout/cas");
return logoutFilter;
}
@Bean
public SingleSignOutFilter singleSignOutFilter() {
SingleSignOutFilter singleSignOutFilter = new SingleSignOutFilter();
singleSignOutFilter.setLogoutCallbackPath("/exit/cas");
singleSignOutFilter.setIgnoreInitConfiguration(true);
return singleSignOutFilter;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/service/CasUserDetailsService.java | security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/service/CasUserDetailsService.java | package com.baeldung.cassecuredapp.service;
import java.util.Collections;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import com.baeldung.cassecuredapp.user.CasUser;
import com.baeldung.cassecuredapp.user.UserRepository;
public class CasUserDetailsService implements UserDetailsService {
@Autowired
private UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// Get the user from the database.
CasUser casUser = getUserFromDatabase(username);
// Create a UserDetails object.
UserDetails userDetails = new User(
casUser.getEmail(),
casUser.getPassword(),
Collections.singletonList(new SimpleGrantedAuthority("ROLE_ADMIN")));
return userDetails;
}
private CasUser getUserFromDatabase(String username) {
return userRepository.findByEmail(username);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/user/UserRepository.java | security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/user/UserRepository.java | package com.baeldung.cassecuredapp.user;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends CrudRepository<CasUser, Long> {
CasUser findByEmail(@Param("email") String email);
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/user/CasUser.java | security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/user/CasUser.java | package com.baeldung.cassecuredapp.user;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class CasUser {
@Id
private Long id;
@Column(nullable = false, unique = true)
private String email;
private String password;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/SecuredController.java | security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/SecuredController.java | package com.baeldung.cassecuredapp.controllers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class SecuredController {
private Logger logger = LoggerFactory.getLogger(SecuredController.class);
@GetMapping("/secured")
public String securedIndex(ModelMap modelMap) {
logger.info("/secured called");
Authentication auth = SecurityContextHolder.getContext()
.getAuthentication();
if(auth.getPrincipal() instanceof UserDetails)
modelMap.put("username", ((UserDetails) auth.getPrincipal()).getUsername());
return "secure/index";
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/AuthController.java | security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/AuthController.java | package com.baeldung.cassecuredapp.controllers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.CookieClearingLogoutHandler;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import static org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY;
@Controller
public class AuthController {
private Logger logger = LoggerFactory.getLogger(AuthController.class);
@GetMapping("/login")
public String login() {
logger.info("/login called");
return "redirect:/secured";
}
@GetMapping("/logout")
public String logout(HttpServletRequest request, HttpServletResponse response, SecurityContextLogoutHandler logoutHandler) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
CookieClearingLogoutHandler cookieClearingLogoutHandler = new CookieClearingLogoutHandler(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
cookieClearingLogoutHandler.logout(request, response, auth);
logoutHandler.logout(request, response, auth);
return "auth/logout";
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/IndexController.java | security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/IndexController.java | package com.baeldung.cassecuredapp.controllers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class IndexController {
private Logger logger = LoggerFactory.getLogger(IndexController.class);
@GetMapping("/")
public String index() {
logger.info("Index controller called");
return "index";
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/config/WebSecurityConfig.java | security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/config/WebSecurityConfig.java | package com.baeldung.cassecuredapp.config;
import org.jasig.cas.client.session.SingleSignOutFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.cas.ServiceProperties;
import org.springframework.security.cas.authentication.CasAuthenticationProvider;
import org.springframework.security.cas.web.CasAuthenticationEntryPoint;
import org.springframework.security.cas.web.CasAuthenticationFilter;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.logout.LogoutFilter;
@EnableWebSecurity
public class WebSecurityConfig {
private Logger logger = LoggerFactory.getLogger(WebSecurityConfig.class);
private SingleSignOutFilter singleSignOutFilter;
private LogoutFilter logoutFilter;
private CasAuthenticationProvider casAuthenticationProvider;
private ServiceProperties serviceProperties;
@Autowired
public WebSecurityConfig(SingleSignOutFilter singleSignOutFilter, LogoutFilter logoutFilter,
CasAuthenticationProvider casAuthenticationProvider,
ServiceProperties serviceProperties) {
this.logoutFilter = logoutFilter;
this.singleSignOutFilter = singleSignOutFilter;
this.serviceProperties = serviceProperties;
this.casAuthenticationProvider = casAuthenticationProvider;
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers( "/secured", "/login").authenticated()
.and()
.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint())
.and()
.addFilterBefore(singleSignOutFilter, CasAuthenticationFilter.class)
.addFilterBefore(logoutFilter, LogoutFilter.class)
.csrf().ignoringAntMatchers("/exit/cas");
return http.build();
}
@Bean
public AuthenticationManager authManager(HttpSecurity http) throws Exception {
return http.getSharedObject(AuthenticationManagerBuilder.class)
.authenticationProvider(casAuthenticationProvider)
.build();
}
public AuthenticationEntryPoint authenticationEntryPoint() {
CasAuthenticationEntryPoint entryPoint = new CasAuthenticationEntryPoint();
entryPoint.setLoginUrl("https://localhost:8443/cas/login");
entryPoint.setServiceProperties(serviceProperties);
return entryPoint;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/cas/cas-server/src/main/java/org/apereo/cas/config/CasOverlayOverrideConfiguration.java | security-modules/cas/cas-server/src/main/java/org/apereo/cas/config/CasOverlayOverrideConfiguration.java | package org.apereo.cas.config;
//import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
//import org.apereo.cas.configuration.CasConfigurationProperties;
@AutoConfiguration
//@EnableConfigurationProperties(CasConfigurationProperties.class)
public class CasOverlayOverrideConfiguration {
/*
@Bean
public MyCustomBean myCustomBean() {
...
}
*/
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/jws/src/main/java/com/example/Hello.java | security-modules/jws/src/main/java/com/example/Hello.java | package com.example;
import javax.swing.*;
public class Hello {
public static void main(String[] args) {
JFrame f = new JFrame("main");
f.setSize(200, 100);
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel("Hello, world!");
f.add(label);
f.setVisible(true);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/jwt/src/test/java/com/baeldung/jwt/replace_deprecated_jwt_parser/JwtParserBuilderUnitTest.java | security-modules/jwt/src/test/java/com/baeldung/jwt/replace_deprecated_jwt_parser/JwtParserBuilderUnitTest.java | package com.baeldung.jwt.replace_deprecated_jwt_parser;
import java.util.Date;
import javax.crypto.SecretKey;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
class JwtParserBuilderUnitTest {
private SecretKey key;
private String token;
@BeforeEach
public void setup() {
key = Keys.secretKeyFor(SignatureAlgorithm.HS256);
token = Jwts.builder()
.setSubject("baeldung")
.setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60))
.signWith(key)
.compact();
}
@Test
void givenJwtParserBuilder_whenParsingTokenInMultipleThreads_thenShouldBeThreadSafe() {
JwtParser parser = Jwts.parserBuilder()
.setSigningKey(key)
.build();
Runnable parseTask = () -> {
Jws<Claims> claimsJws = parser.parseClaimsJws(token);
Claims claims = claimsJws.getBody();
Assertions.assertEquals("baeldung", claims.getSubject());
};
Thread thread1 = new Thread(parseTask);
Thread thread2 = new Thread(parseTask);
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
Assertions.fail("Thread execution was interrupted");
}
}
@Test
void givenJwtParserBuilder_whenRequiringSpecificClaim_thenShouldParseSuccessfully() {
JwtParser parser = Jwts.parserBuilder()
.setSigningKey(key)
.build();
Claims claims = parser.parseClaimsJws(token)
.getBody();
Assertions.assertEquals("baeldung", claims.getSubject());
}
@Test
void givenJwtParserBuilder_whenRequiringNonExistentClaim_thenShouldHandleGracefully() {
JwtParser parser = Jwts.parserBuilder()
.setSigningKey(key)
.build();
try {
Claims claims = parser.parseClaimsJws(token)
.getBody();
Assertions.assertNull(claims.get("non-existent-claim"));
} catch (Exception e) {
Assertions.assertEquals("JWT claims string is empty.", e.getMessage());
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/jwt/src/test/java/com/baeldung/jwt/replace_deprecated_jwt_parser/DeprecatedParserUnitTest.java | security-modules/jwt/src/test/java/com/baeldung/jwt/replace_deprecated_jwt_parser/DeprecatedParserUnitTest.java | package com.baeldung.jwt.replace_deprecated_jwt_parser;
import static org.junit.Assert.assertEquals;
import java.util.Date;
import javax.crypto.SecretKey;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
class DeprecatedParserUnitTest {
private SecretKey key;
private String token;
@BeforeEach
public void setup() {
key = Keys.secretKeyFor(SignatureAlgorithm.HS256);
token = Jwts.builder()
.setSubject("baeldung")
.setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60))
.signWith(key)
.compact();
}
@Test
void givenDeprecatedParser_whenParsingTokenInMultipleThreads_thenMayNotBeThreadSafe() {
JwtParser parser = Jwts.parser()
.setSigningKey(key);
Runnable parseTask = () -> {
Jws<Claims> claimsJws = parser.parseClaimsJws(token);
Claims claims = claimsJws.getBody();
assertEquals("baeldung", claims.getSubject());
};
Thread thread1 = new Thread(parseTask);
Thread thread2 = new Thread(parseTask);
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
Assertions.fail("Thread execution was interrupted");
}
}
@Test
void givenDeprecatedParser_whenRequiringSpecificClaim_thenShouldParseSuccessfully() {
JwtParser parser = Jwts.parser()
.setSigningKey(key);
Claims claims = parser.parseClaimsJws(token)
.getBody();
Assertions.assertEquals("baeldung", claims.getSubject());
}
@Test
public void givenDeprecatedParser_whenRequiringNonExistentClaim_thenShouldFail() {
JwtParser parser = Jwts.parser()
.setSigningKey(key);
try {
Claims claims = parser.parseClaimsJws(token)
.getBody();
Assertions.assertEquals(null, claims.get("non-existent-claim"));
} catch (Exception e) {
Assertions.assertEquals("JWT claims string is empty.", e.getMessage());
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/jwt/src/test/java/com/baeldung/jwt/auth0/Auth0JsonWebTokenUnitTest.java | security-modules/jwt/src/test/java/com/baeldung/jwt/auth0/Auth0JsonWebTokenUnitTest.java | package com.baeldung.jwt.auth0;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.Date;
import org.junit.Ignore;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.IncorrectClaimException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
public class Auth0JsonWebTokenUnitTest {
private static final String SECRET = "baeldung";
private static final String SECRET_NEW = "baeldung.com";
private static final String ISSUER = "Baeldung";
private static final String DATA_CLAIM = "userId";
private static final String DATA = "1234";
private static Algorithm algorithm;
private static Algorithm algorithmWithDifferentSecret;
private static JWTVerifier verifier;
private static String jwtToken;
@BeforeAll
public static void setUp() {
algorithm = Algorithm.HMAC256(SECRET);
algorithmWithDifferentSecret = Algorithm.HMAC256(SECRET_NEW);
verifier = JWT.require(algorithm)
.withIssuer(ISSUER)
.build();
}
private static boolean isJWTExpired(DecodedJWT decodedJWT) {
Date expiresAt = decodedJWT.getExpiresAt();
return expiresAt.getTime() < System.currentTimeMillis();
}
private static DecodedJWT verifyJWT(String jwtToken) {
DecodedJWT decodedJWT = verifier.verify(jwtToken);
return decodedJWT;
}
@Test
public void givenJWT_whenNotExpired_thenCheckingIfNotExpired() {
jwtToken = JWT.create()
.withIssuer(ISSUER)
.withClaim(DATA_CLAIM, DATA)
.withExpiresAt(new Date(System.currentTimeMillis() + 1000L))
.sign(algorithm);
DecodedJWT decodedJWT = verifyJWT(jwtToken);
assertNotNull(decodedJWT);
assertFalse(isJWTExpired(decodedJWT));
}
@Test
public void givenJWT_whenExpired_thenCheckingIfExpired() {
jwtToken = JWT.create()
.withIssuer(ISSUER)
.withClaim(DATA_CLAIM, DATA)
.withExpiresAt(new Date(System.currentTimeMillis() - 1000L))
.sign(algorithm);
assertThrows(TokenExpiredException.class, () -> {
verifyJWT(jwtToken);
});
}
@Test
public void givenJWT_whenCreatedWithCustomClaim_thenCheckingForCustomClaim() {
jwtToken = JWT.create()
.withIssuer(ISSUER)
.withClaim(DATA_CLAIM, DATA)
.withExpiresAt(new Date(System.currentTimeMillis() + 1000L))
.sign(algorithm);
DecodedJWT decodedJWT = verifyJWT(jwtToken);
assertNotNull(decodedJWT);
Claim claim = decodedJWT.getClaim(DATA_CLAIM);
assertEquals(DATA, claim.asString());
}
//Need to fix with JAVA-24552
@Ignore
public void givenJWT_whenCreatedWithNotBefore_thenThrowException() {
jwtToken = JWT.create()
.withIssuer(ISSUER)
.withClaim(DATA_CLAIM, DATA)
.withNotBefore(new Date(System.currentTimeMillis() + 10000L))
.sign(algorithm);
assertThrows(IncorrectClaimException.class, () -> {
verifyJWT(jwtToken);
});
}
@Test
public void givenJWT_whenVerifyingUsingDifferentSecret_thenThrowException() {
jwtToken = JWT.create()
.withIssuer(ISSUER)
.withClaim(DATA_CLAIM, DATA)
.withExpiresAt(new Date(System.currentTimeMillis() + 1000L))
.sign(algorithmWithDifferentSecret);
assertThrows(SignatureVerificationException.class, () -> {
verifyJWT(jwtToken);
});
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/jwt/src/test/java/com/baeldung/jwt/auth0/JWTDecodeUnitTest.java | security-modules/jwt/src/test/java/com/baeldung/jwt/auth0/JWTDecodeUnitTest.java | package com.baeldung.jwt.auth0;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Date;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
public class JWTDecodeUnitTest {
private static final String SECRET = "baeldung";
private static final String ISSUER = "Baeldung";
private static final long TOKEN_VALIDITY_IN_MILLIS = 1000L;
private static Algorithm algorithm;
private static JWTVerifier verifier;
private static String jwtToken;
@BeforeAll
public static void setUp() {
algorithm = Algorithm.HMAC256(SECRET);
verifier = JWT.require(algorithm)
.withIssuer(ISSUER)
.build();
}
private static boolean isJWTExpired(DecodedJWT decodedJWT) {
Date expiresAt = decodedJWT.getExpiresAt();
return expiresAt.before(new Date());
}
private static DecodedJWT decodedJWT(String jwtToken) {
return JWT.decode(jwtToken);
}
@Test
public void givenNotExpiredJWT_whenDecoded_thenCheckingIfNotExpired() {
jwtToken = JWT.create()
.withIssuer(ISSUER)
.withExpiresAt(new Date(System.currentTimeMillis() + TOKEN_VALIDITY_IN_MILLIS))
.sign(algorithm);
DecodedJWT decodedJWT = decodedJWT(jwtToken);
assertNotNull(decodedJWT);
assertFalse(isJWTExpired(decodedJWT));
}
@Test
public void givenExpiredJWT_whenDecoded_thenCheckingIfExpired() {
jwtToken = JWT.create()
.withIssuer(ISSUER)
.withExpiresAt(new Date(System.currentTimeMillis() - TOKEN_VALIDITY_IN_MILLIS))
.sign(algorithm);
DecodedJWT decodedJWT = decodedJWT(jwtToken);
assertNotNull(decodedJWT);
assertTrue(isJWTExpired(decodedJWT));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/jwt/src/main/java/com/baeldung/jwt/replace_deprecated_jwt_parser/DeprecatedParser.java | security-modules/jwt/src/main/java/com/baeldung/jwt/replace_deprecated_jwt_parser/DeprecatedParser.java | package com.baeldung.jwt.replace_deprecated_jwt_parser;
import java.util.Date;
import javax.crypto.SecretKey;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
public class DeprecatedParser {
public static void main(String args[]) {
SecretKey key = Keys.secretKeyFor(SignatureAlgorithm.HS256);
String token = Jwts.builder()
.setSubject("baeldung")
.setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60))
.signWith(key)
.compact();
JwtParser parser = Jwts.parser()
.setSigningKey(key);
Claims claims = parser.parseClaimsJws(token)
.getBody();
System.out.println("Claims: " + claims);
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/jwt/src/main/java/com/baeldung/jwt/replace_deprecated_jwt_parser/JwtParserBuilder.java | security-modules/jwt/src/main/java/com/baeldung/jwt/replace_deprecated_jwt_parser/JwtParserBuilder.java | package com.baeldung.jwt.replace_deprecated_jwt_parser;
import java.util.Date;
import javax.crypto.SecretKey;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
public class JwtParserBuilder {
public static void main(String[] args) {
SecretKey key = Keys.secretKeyFor(SignatureAlgorithm.HS256);
String token = Jwts.builder()
.setSubject("username")
.setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60))
.signWith(key)
.compact();
JwtParser parser = Jwts.parserBuilder()
.setSigningKey(key)
.build();
Claims claims = parser.parseClaimsJws(token)
.getBody();
System.out.println("Claims: " + claims);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/jwt/src/main/java/com/baeldung/jwt/auth0/JWTDecode.java | security-modules/jwt/src/main/java/com/baeldung/jwt/auth0/JWTDecode.java | package com.baeldung.jwt.auth0;
import java.util.Date;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
public class JWTDecode {
private static final String SECRET = "baeldung";
private static final String ISSUER = "Baeldung";
private static final String SUBJECT = "Baeldung Details";
private static final long TOKEN_VALIDITY_IN_MILLIS = 500L;
private static Algorithm algorithm;
private static JWTVerifier verifier;
public static void initialize() {
algorithm = Algorithm.HMAC256(SECRET);
verifier = JWT.require(algorithm)
.withIssuer(ISSUER)
.build();
}
private static String createJWT() {
String jwtToken = JWT.create()
.withIssuer(ISSUER)
.withSubject(SUBJECT)
.withIssuedAt(new Date())
.withExpiresAt(new Date(System.currentTimeMillis() + TOKEN_VALIDITY_IN_MILLIS))
.sign(algorithm);
return jwtToken;
}
private static DecodedJWT verifyJWT(String jwtToken) {
try {
DecodedJWT decodedJWT = verifier.verify(jwtToken);
return decodedJWT;
} catch (JWTVerificationException e) {
System.out.println(e.getMessage());
}
return null;
}
private static DecodedJWT decodedJWT(String jwtToken) {
try {
DecodedJWT decodedJWT = JWT.decode(jwtToken);
return decodedJWT;
} catch (JWTDecodeException e) {
System.out.println(e.getMessage());
}
return null;
}
private static boolean isJWTExpired(DecodedJWT decodedJWT) {
Date expiresAt = decodedJWT.getExpiresAt();
return expiresAt.before(new Date());
}
public static void main(String args[]) throws InterruptedException {
initialize();
String jwtToken = createJWT();
System.out.println("Created JWT : " + jwtToken);
Thread.sleep(1000L);
DecodedJWT decodedJWT = verifyJWT(jwtToken);
if (decodedJWT == null) {
System.out.println("JWT Verification Failed");
}
decodedJWT = decodedJWT(jwtToken);
if (decodedJWT != null) {
System.out.println("Token Issued At : " + decodedJWT.getIssuedAt());
System.out.println("Token Expires At : " + decodedJWT.getExpiresAt());
Boolean isExpired = isJWTExpired(decodedJWT);
System.out.println("Is Expired : " + isExpired);
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/jwt/src/main/java/com/baeldung/jwt/auth0/Auth0JsonWebToken.java | security-modules/jwt/src/main/java/com/baeldung/jwt/auth0/Auth0JsonWebToken.java | package com.baeldung.jwt.auth0;
import java.util.Date;
import java.util.UUID;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
public class Auth0JsonWebToken {
private static final String SECRET = "baeldung";
private static final String ISSUER = "Baeldung";
private static final String SUBJECT = "Baeldung Details";
private static final String DATA_CLAIM = "userId";
private static final String DATA = "1234";
private static final long TOKEN_VALIDITY_IN_MILLIS = 5000L;
private static Algorithm algorithm;
private static JWTVerifier verifier;
public static void initialize() {
algorithm = Algorithm.HMAC256(SECRET);
verifier = JWT.require(algorithm)
.withIssuer(ISSUER)
.build();
}
private static String createJWT() {
String jwtToken = JWT.create()
.withIssuer(ISSUER)
.withSubject(SUBJECT)
.withClaim(DATA_CLAIM, DATA)
.withIssuedAt(new Date())
.withExpiresAt(new Date(System.currentTimeMillis() + TOKEN_VALIDITY_IN_MILLIS))
.withJWTId(UUID.randomUUID()
.toString())
.withNotBefore(new Date(System.currentTimeMillis() + 1000L))
.sign(algorithm);
return jwtToken;
}
private static DecodedJWT verifyJWT(String jwtToken) {
try {
DecodedJWT decodedJWT = verifier.verify(jwtToken);
return decodedJWT;
} catch (JWTVerificationException e) {
System.out.println(e.getMessage());
}
return null;
}
private static boolean isJWTExpired(DecodedJWT decodedJWT) {
Date expiresAt = decodedJWT.getExpiresAt();
return expiresAt.getTime() < System.currentTimeMillis();
}
private static String getClaim(DecodedJWT decodedJWT, String claimName) {
Claim claim = decodedJWT.getClaim(claimName);
return claim != null ? claim.asString() : null;
}
public static void main(String args[]) throws InterruptedException {
initialize();
String jwtToken = createJWT();
System.out.println("Created JWT : " + jwtToken);
DecodedJWT decodedJWT = verifyJWT(jwtToken);
if (decodedJWT == null) {
System.out.println("JWT Verification Failed");
}
Thread.sleep(1000L);
decodedJWT = verifyJWT(jwtToken);
if (decodedJWT != null) {
System.out.println("Token Issued At : " + decodedJWT.getIssuedAt());
System.out.println("Token Expires At : " + decodedJWT.getExpiresAt());
System.out.println("Subject : " + decodedJWT.getSubject());
System.out.println("Data : " + getClaim(decodedJWT, DATA_CLAIM));
System.out.println("Header : " + decodedJWT.getHeader());
System.out.println("Payload : " + decodedJWT.getPayload());
System.out.println("Signature : " + decodedJWT.getSignature());
System.out.println("Algorithm : " + decodedJWT.getAlgorithm());
System.out.println("JWT Id : " + decodedJWT.getId());
Boolean isExpired = isJWTExpired(decodedJWT);
System.out.println("Is Expired : " + isExpired);
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/AdminServlet.java | security-modules/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/AdminServlet.java | package com.baeldung.javaee.security;
import javax.inject.Inject;
import javax.security.enterprise.SecurityContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.HttpConstraint;
import javax.servlet.annotation.ServletSecurity;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.Principal;
@WebServlet("/admin")
@ServletSecurity(value = @HttpConstraint(rolesAllowed = {"admin_role"}))
public class AdminServlet extends HttpServlet {
@Inject
SecurityContext securityContext;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().append("getCallerPrincipal :" + securityContext.getCallerPrincipal() + "\n");
response.getWriter().append("CustomPrincipal :" + securityContext.getPrincipalsByType(CustomPrincipal.class) + "\n");
response.getWriter().append("Principal :" + securityContext.getPrincipalsByType(Principal.class) + "\n");
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/CustomAuthentication.java | security-modules/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/CustomAuthentication.java | package com.baeldung.javaee.security;
import javax.enterprise.context.ApplicationScoped;
import javax.security.enterprise.AuthenticationException;
import javax.security.enterprise.AuthenticationStatus;
import javax.security.enterprise.authentication.mechanism.http.HttpAuthenticationMechanism;
import javax.security.enterprise.authentication.mechanism.http.HttpMessageContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashSet;
@ApplicationScoped
public class CustomAuthentication implements HttpAuthenticationMechanism {
@Override
public AuthenticationStatus validateRequest(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse,
HttpMessageContext httpMessageContext) throws AuthenticationException {
String username = httpServletRequest.getParameter("username");
String password = httpServletRequest.getParameter("password");
//Mocking UserDetail, but in real life, we can find it from a database.
UserDetail userDetail = findByUserNameAndPassword(username, password);
if (userDetail != null) {
return httpMessageContext.notifyContainerAboutLogin(
new CustomPrincipal(userDetail),
new HashSet<>(userDetail.getRoles()));
}
return httpMessageContext.responseUnauthorized();
}
private UserDetail findByUserNameAndPassword(String username, String password) {
UserDetail userDetail = new UserDetail("uid_10", username, password);
userDetail.addRole("admin_role");
return userDetail;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/CustomPrincipal.java | security-modules/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/CustomPrincipal.java | package com.baeldung.javaee.security;
import java.security.Principal;
public class CustomPrincipal implements Principal {
private UserDetail userDetail;
public CustomPrincipal(UserDetail userDetail) {
this.userDetail = userDetail;
}
@Override
public String getName() {
return userDetail.getLogin();
}
@Override
public String toString() {
return this.getClass().getSimpleName() + ":" + getName();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/UserDetail.java | security-modules/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/UserDetail.java | package com.baeldung.javaee.security;
import java.util.ArrayList;
import java.util.List;
public class UserDetail {
private String uid;
private String login;
private String password;
private List<String> roles = new ArrayList<>();
//...
UserDetail(String uid, String login, String password) {
this.uid = uid;
this.login = login;
this.password = password;
}
public String getUid() {
return uid;
}
public String getLogin() {
return login;
}
public String getPassword() {
return password;
}
public List<String> getRoles() {
return roles;
}
public void addRole(String role) {
roles.add(role);
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/AppConfig.java | security-modules/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/AppConfig.java | package com.baeldung.javaee.security;
import javax.enterprise.context.ApplicationScoped;
@ApplicationScoped
public class AppConfig {
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/java-ee-8-security-api/app-auth-form-store-ldap/src/main/java/com/baeldung/javaee/security/AdminServlet.java | security-modules/java-ee-8-security-api/app-auth-form-store-ldap/src/main/java/com/baeldung/javaee/security/AdminServlet.java | package com.baeldung.javaee.security;
import javax.servlet.ServletException;
import javax.servlet.annotation.HttpConstraint;
import javax.servlet.annotation.ServletSecurity;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/admin")
@ServletSecurity(value = @HttpConstraint(rolesAllowed = {"admin_role"}))
public class AdminServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().append("User :" + request.getUserPrincipal().getName() + "\n");
response.getWriter().append("User in Role user_role :" + request.isUserInRole("user_role") + "\n");
response.getWriter().append("User in Role admin_role :" + request.isUserInRole("admin_role"));
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/java-ee-8-security-api/app-auth-form-store-ldap/src/main/java/com/baeldung/javaee/security/LdapSetupServlet.java | security-modules/java-ee-8-security-api/app-auth-form-store-ldap/src/main/java/com/baeldung/javaee/security/LdapSetupServlet.java | package com.baeldung.javaee.security;
import com.unboundid.ldap.listener.InMemoryDirectoryServer;
import com.unboundid.ldap.listener.InMemoryDirectoryServerConfig;
import com.unboundid.ldap.listener.InMemoryListenerConfig;
import com.unboundid.ldap.sdk.LDAPException;
import com.unboundid.ldif.LDIFReader;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
@WebServlet(value = "/init-ldap", loadOnStartup = 1)
public class LdapSetupServlet extends HttpServlet {
private InMemoryDirectoryServer inMemoryDirectoryServer;
@Override
public void init() throws ServletException {
super.init();
initLdap();
System.out.println("@@@START_");
}
private void initLdap() {
try {
InMemoryDirectoryServerConfig config = new InMemoryDirectoryServerConfig("dc=baeldung,dc=com");
config.setListenerConfigs(InMemoryListenerConfig.createLDAPConfig("default", 10389));
config.setSchema(null);
inMemoryDirectoryServer = new InMemoryDirectoryServer(config);
inMemoryDirectoryServer.importFromLDIF(true,
new LDIFReader(this.getClass().getResourceAsStream("/users.ldif")));
inMemoryDirectoryServer.startListening();
} catch (LDAPException e) {
e.printStackTrace();
}
}
@Override
public void destroy() {
super.destroy();
inMemoryDirectoryServer.shutDown(true);
System.out.println("@@@END");
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/java-ee-8-security-api/app-auth-form-store-ldap/src/main/java/com/baeldung/javaee/security/AppConfig.java | security-modules/java-ee-8-security-api/app-auth-form-store-ldap/src/main/java/com/baeldung/javaee/security/AppConfig.java | package com.baeldung.javaee.security;
import javax.enterprise.context.ApplicationScoped;
import javax.security.enterprise.authentication.mechanism.http.FormAuthenticationMechanismDefinition;
import javax.security.enterprise.authentication.mechanism.http.LoginToContinue;
import javax.security.enterprise.identitystore.LdapIdentityStoreDefinition;
@FormAuthenticationMechanismDefinition(
loginToContinue = @LoginToContinue(
loginPage = "/login.html",
errorPage = "/login-error.html"
)
)
@LdapIdentityStoreDefinition(
url = "ldap://localhost:10389",
callerBaseDn = "ou=caller,dc=baeldung,dc=com",
groupSearchBase = "ou=group,dc=baeldung,dc=com",
groupSearchFilter = "(&(member=%s)(objectClass=groupOfNames))"
)
@ApplicationScoped
public class AppConfig {
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/java-ee-8-security-api/app-auth-form-store-ldap/src/main/java/com/baeldung/javaee/security/UserServlet.java | security-modules/java-ee-8-security-api/app-auth-form-store-ldap/src/main/java/com/baeldung/javaee/security/UserServlet.java | package com.baeldung.javaee.security;
import javax.servlet.ServletException;
import javax.servlet.annotation.HttpConstraint;
import javax.servlet.annotation.ServletSecurity;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/user")
@ServletSecurity(value = @HttpConstraint(rolesAllowed = {"user_role"}))
public class UserServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().append("User :" + request.getUserPrincipal().getName() + "\n");
response.getWriter().append("User in Role user_role :" + request.isUserInRole("user_role") + "\n");
response.getWriter().append("User in Role admin_role :" + request.isUserInRole("admin_role"));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/LoginBean.java | security-modules/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/LoginBean.java | package com.baeldung.javaee.security;
import javax.enterprise.context.RequestScoped;
import javax.faces.annotation.FacesConfig;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import javax.security.enterprise.AuthenticationStatus;
import javax.security.enterprise.SecurityContext;
import javax.security.enterprise.credential.Credential;
import javax.security.enterprise.credential.Password;
import javax.security.enterprise.credential.UsernamePasswordCredential;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import static javax.faces.application.FacesMessage.SEVERITY_ERROR;
import static javax.security.enterprise.AuthenticationStatus.SEND_CONTINUE;
import static javax.security.enterprise.AuthenticationStatus.SEND_FAILURE;
import static javax.security.enterprise.authentication.mechanism.http.AuthenticationParameters.withParams;
@FacesConfig
@Named
@RequestScoped
public class LoginBean {
@Inject
private SecurityContext securityContext;
@Inject
private FacesContext facesContext;
@NotNull
private String username;
@NotNull
private String password;
public void login() {
Credential credential = new UsernamePasswordCredential(username, new Password(password));
AuthenticationStatus status = securityContext.authenticate(
getHttpRequestFromFacesContext(),
getHttpResponseFromFacesContext(),
withParams().credential(credential));
if (status.equals(SEND_CONTINUE)) {
facesContext.responseComplete();
} else if (status.equals(SEND_FAILURE)) {
facesContext.addMessage(null,
new FacesMessage(SEVERITY_ERROR, "Authentication failed", null));
}
}
private HttpServletRequest getHttpRequestFromFacesContext() {
return (HttpServletRequest) facesContext
.getExternalContext()
.getRequest();
}
private HttpServletResponse getHttpResponseFromFacesContext() {
return (HttpServletResponse) facesContext
.getExternalContext()
.getResponse();
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/InMemoryIdentityStore4Authorization.java | security-modules/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/InMemoryIdentityStore4Authorization.java | package com.baeldung.javaee.security;
import javax.enterprise.context.ApplicationScoped;
import javax.security.enterprise.identitystore.CredentialValidationResult;
import javax.security.enterprise.identitystore.IdentityStore;
import java.util.*;
@ApplicationScoped
class InMemoryIdentityStore4Authorization implements IdentityStore {
private Map<String, List<String>> userRoles = new HashMap<>();
public InMemoryIdentityStore4Authorization() {
//Init users
// from a file or hardcoded
init();
}
private void init() {
//user1
List<String> roles = new ArrayList<>();
roles.add("USER_ROLE");
userRoles.put("user", roles);
//user2
roles = new ArrayList<>();
roles.add("USER_ROLE");
roles.add("ADMIN_ROLE");
userRoles.put("admin", roles);
}
@Override
public int priority() {
return 80;
}
@Override
public Set<ValidationType> validationTypes() {
return EnumSet.of(ValidationType.PROVIDE_GROUPS);
}
@Override
public Set<String> getCallerGroups(CredentialValidationResult validationResult) {
List<String> roles = userRoles.get(validationResult.getCallerPrincipal().getName());
return new HashSet<>(roles);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/InMemoryIdentityStore4Authentication.java | security-modules/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/InMemoryIdentityStore4Authentication.java | package com.baeldung.javaee.security;
import javax.enterprise.context.ApplicationScoped;
import javax.security.enterprise.credential.UsernamePasswordCredential;
import javax.security.enterprise.identitystore.CredentialValidationResult;
import javax.security.enterprise.identitystore.IdentityStore;
import java.util.*;
import static javax.security.enterprise.identitystore.CredentialValidationResult.INVALID_RESULT;
@ApplicationScoped
public class InMemoryIdentityStore4Authentication implements IdentityStore {
private Map<String, String> users = new HashMap<>();
public InMemoryIdentityStore4Authentication() {
//Init users
// from a file or hardcoded
init();
}
private void init() {
//user1
users.put("user", "pass0");
//user2
users.put("admin", "pass1");
}
@Override
public int priority() {
return 70;
}
@Override
public Set<ValidationType> validationTypes() {
return EnumSet.of(ValidationType.VALIDATE);
}
public CredentialValidationResult validate(UsernamePasswordCredential credential) {
String password = users.get(credential.getCaller());
if (password != null && password.equals(credential.getPasswordAsString())) {
return new CredentialValidationResult(credential.getCaller());
}
return INVALID_RESULT;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/AppConfig.java | security-modules/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/AppConfig.java | package com.baeldung.javaee.security;
import javax.enterprise.context.ApplicationScoped;
import javax.faces.annotation.FacesConfig;
import javax.security.enterprise.authentication.mechanism.http.CustomFormAuthenticationMechanismDefinition;
import javax.security.enterprise.authentication.mechanism.http.LoginToContinue;
@CustomFormAuthenticationMechanismDefinition(
loginToContinue = @LoginToContinue(
loginPage = "/login.xhtml",
errorPage = "/login-error.html"
)
)
@ApplicationScoped
public class AppConfig {
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/WelcomeServlet.java | security-modules/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/WelcomeServlet.java | package com.baeldung.javaee.security;
import javax.inject.Inject;
import javax.security.enterprise.SecurityContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.HttpConstraint;
import javax.servlet.annotation.ServletSecurity;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/welcome")
@ServletSecurity(@HttpConstraint(rolesAllowed = "USER_ROLE"))
public class WelcomeServlet extends HttpServlet {
@Inject
private SecurityContext securityContext;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
securityContext.hasAccessToWebResource("/protectedServlet", "GET");
resp.getWriter().write("" +
"Authentication type :" + req.getAuthType() + "\n" +
"Caller Principal :" + securityContext.getCallerPrincipal() + "\n" +
"User in Role USER_ROLE :" + securityContext.isCallerInRole("USER_ROLE") + "\n" +
"User in Role ADMIN_ROLE :" + securityContext.isCallerInRole("ADMIN_ROLE") + "\n" +
"");
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/AdminServlet.java | security-modules/java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/AdminServlet.java | package com.baeldung.javaee.security;
import javax.servlet.annotation.HttpConstraint;
import javax.servlet.annotation.ServletSecurity;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/admin")
@ServletSecurity(value = @HttpConstraint(rolesAllowed = {"admin_role"}))
public class AdminServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.getWriter().append("User :" + request.getUserPrincipal().getName() + "\n");
response.getWriter().append("User in Role user_role :" + request.isUserInRole("user_role") + "\n");
response.getWriter().append("User in Role admin_role :" + request.isUserInRole("admin_role"));
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/DatabaseSetupServlet.java | security-modules/java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/DatabaseSetupServlet.java | package com.baeldung.javaee.security;
import javax.annotation.Resource;
import javax.annotation.sql.DataSourceDefinition;
import javax.inject.Inject;
import javax.security.enterprise.identitystore.Pbkdf2PasswordHash;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
@DataSourceDefinition(
name = "java:comp/env/jdbc/securityDS",
className = "org.h2.jdbcx.JdbcDataSource",
url = "jdbc:h2:~/securityTest;MODE=Oracle"
)
@WebServlet(value = "/init", loadOnStartup = 0)
public class DatabaseSetupServlet extends HttpServlet {
@Resource(lookup = "java:comp/env/jdbc/securityDS")
private DataSource dataSource;
@Inject
private Pbkdf2PasswordHash passwordHash;
@Override
public void init() throws ServletException {
super.init();
initdb();
}
private void initdb() {
executeUpdate(dataSource, "DROP TABLE IF EXISTS USERS");
executeUpdate(dataSource, "DROP TABLE IF EXISTS GROUPS");
executeUpdate(dataSource, "CREATE TABLE IF NOT EXISTS USERS(username VARCHAR(64) PRIMARY KEY, password VARCHAR(255))");
executeUpdate(dataSource, "CREATE TABLE IF NOT EXISTS GROUPS(username VARCHAR(64), GROUPNAME VARCHAR(64))");
executeUpdate(dataSource, "INSERT INTO USERS VALUES('admin', '" + passwordHash.generate("passadmin".toCharArray()) + "')");
executeUpdate(dataSource, "INSERT INTO USERS VALUES('user', '" + passwordHash.generate("passuser".toCharArray()) + "')");
executeUpdate(dataSource, "INSERT INTO GROUPS VALUES('admin', 'admin_role')");
executeUpdate(dataSource, "INSERT INTO GROUPS VALUES('admin', 'user_role')");
executeUpdate(dataSource, "INSERT INTO GROUPS VALUES('user', 'user_role')");
}
private void executeUpdate(DataSource dataSource, String query) {
try (Connection connection = dataSource.getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(query)) {
statement.executeUpdate();
}
} catch (SQLException e) {
throw new IllegalStateException(e);
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/AppConfig.java | security-modules/java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/AppConfig.java | package com.baeldung.javaee.security;
import javax.enterprise.context.ApplicationScoped;
import javax.security.enterprise.authentication.mechanism.http.BasicAuthenticationMechanismDefinition;
import javax.security.enterprise.identitystore.DatabaseIdentityStoreDefinition;
@BasicAuthenticationMechanismDefinition(realmName = "defaultRealm")
@DatabaseIdentityStoreDefinition(
dataSourceLookup = "java:comp/env/jdbc/securityDS",
callerQuery = "select password from users where username = ?",
groupsQuery = "select GROUPNAME from groups where username = ?"
)
@ApplicationScoped
public class AppConfig {
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/UserServlet.java | security-modules/java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/UserServlet.java | package com.baeldung.javaee.security;
import javax.servlet.ServletException;
import javax.servlet.annotation.HttpConstraint;
import javax.servlet.annotation.ServletSecurity;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/user")
@ServletSecurity(value = @HttpConstraint(rolesAllowed = {"user_role"}))
public class UserServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().append("User :" + request.getUserPrincipal().getName() + "\n");
response.getWriter().append("User in Role user_role :" + request.isUserInRole("user_role") + "\n");
response.getWriter().append("User in Role admin_role :" + request.isUserInRole("admin_role"));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/apache-shiro/src/test/java/com/baeldung/comparison/shiro/SpringContextTest.java | security-modules/apache-shiro/src/test/java/com/baeldung/comparison/shiro/SpringContextTest.java | package com.baeldung.comparison.shiro;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import com.baeldung.comparison.shiro.ShiroApplication;
@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = { ShiroApplication.class })
public class SpringContextTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/apache-shiro/src/test/java/com/baeldung/comparison/springsecurity/SpringContextTest.java | security-modules/apache-shiro/src/test/java/com/baeldung/comparison/springsecurity/SpringContextTest.java | package com.baeldung.comparison.springsecurity;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import com.baeldung.comparison.springsecurity.Application;
@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = { Application.class })
public class SpringContextTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/apache-shiro/src/main/java/com/baeldung/comparison/shiro/ShiroApplication.java | security-modules/apache-shiro/src/main/java/com/baeldung/comparison/shiro/ShiroApplication.java | package com.baeldung.comparison.shiro;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.context.annotation.Bean;
@SpringBootApplication(exclude = SecurityAutoConfiguration.class)
public class ShiroApplication {
public static void main(String... args) {
SpringApplication.run(ShiroApplication.class, args);
}
@Bean
public Realm customRealm() {
return new CustomRealm();
}
@Bean
public ShiroFilterChainDefinition shiroFilterChainDefinition() {
DefaultShiroFilterChainDefinition filter = new DefaultShiroFilterChainDefinition();
filter.addPathDefinition("/home", "authc");
filter.addPathDefinition("/**", "anon");
return filter;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/apache-shiro/src/main/java/com/baeldung/comparison/shiro/CustomRealm.java | security-modules/apache-shiro/src/main/java/com/baeldung/comparison/shiro/CustomRealm.java | package com.baeldung.comparison.shiro;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.jdbc.JdbcRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CustomRealm extends JdbcRealm {
private Logger logger = LoggerFactory.getLogger(CustomRealm.class);
private Map<String, String> credentials = new HashMap<>();
private Map<String, Set<String>> roles = new HashMap<>();
private Map<String, Set<String>> permissions = new HashMap<>();
{
credentials.put("Tom", "password");
credentials.put("Jerry", "password");
roles.put("Jerry", new HashSet<>(Arrays.asList("ADMIN")));
roles.put("Tom", new HashSet<>(Arrays.asList("USER")));
permissions.put("ADMIN", new HashSet<>(Arrays.asList("READ", "WRITE")));
permissions.put("USER", new HashSet<>(Arrays.asList("READ")));
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
UsernamePasswordToken userToken = (UsernamePasswordToken) token;
if (userToken.getUsername() == null || userToken.getUsername()
.isEmpty() || !credentials.containsKey(userToken.getUsername())) {
throw new UnknownAccountException("User doesn't exist");
}
return new SimpleAuthenticationInfo(userToken.getUsername(), credentials.get(userToken.getUsername()), getName());
}
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
Set<String> roles = new HashSet<>();
Set<String> permissions = new HashSet<>();
for (Object user : principals) {
try {
roles.addAll(getRoleNamesForUser(null, (String) user));
permissions.addAll(getPermissions(null, null, roles));
} catch (SQLException e) {
logger.error(e.getMessage());
}
}
SimpleAuthorizationInfo authInfo = new SimpleAuthorizationInfo(roles);
authInfo.setStringPermissions(permissions);
return authInfo;
}
@Override
protected Set<String> getRoleNamesForUser(Connection conn, String username) throws SQLException {
if (!roles.containsKey(username)) {
throw new SQLException("User doesn't exist");
}
return roles.get(username);
}
@Override
protected Set<String> getPermissions(Connection conn, String username, Collection<String> roles) throws SQLException {
Set<String> userPermissions = new HashSet<>();
for (String role : roles) {
if (!permissions.containsKey(role)) {
throw new SQLException("Role doesn't exist");
}
userPermissions.addAll(permissions.get(role));
}
return userPermissions;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/apache-shiro/src/main/java/com/baeldung/comparison/shiro/controllers/ShiroController.java | security-modules/apache-shiro/src/main/java/com/baeldung/comparison/shiro/controllers/ShiroController.java | package com.baeldung.comparison.shiro.controllers;
import javax.servlet.http.HttpServletRequest;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.baeldung.comparison.shiro.models.UserCredentials;
@Controller
public class ShiroController {
private Logger logger = LoggerFactory.getLogger(ShiroController.class);
@GetMapping("/")
public String getIndex() {
return "comparison/index";
}
@GetMapping("/login")
public String showLoginPage() {
return "comparison/login";
}
@PostMapping("/login")
public String doLogin(HttpServletRequest req, UserCredentials credentials, RedirectAttributes attr) {
Subject subject = SecurityUtils.getSubject();
if (!subject.isAuthenticated()) {
UsernamePasswordToken token = new UsernamePasswordToken(credentials.getUsername(), credentials.getPassword());
try {
subject.login(token);
} catch (AuthenticationException ae) {
logger.error(ae.getMessage());
attr.addFlashAttribute("error", "Invalid Credentials");
return "redirect:/login";
}
}
return "redirect:/home";
}
@GetMapping("/home")
public String getMeHome(Model model) {
addUserAttributes(model);
return "comparison/home";
}
@GetMapping("/admin")
public String adminOnly(Model model) {
addUserAttributes(model);
Subject currentUser = SecurityUtils.getSubject();
if (currentUser.hasRole("ADMIN")) {
model.addAttribute("adminContent", "only admin can view this");
}
return "comparison/home";
}
@PostMapping("/logout")
public String logout() {
Subject subject = SecurityUtils.getSubject();
subject.logout();
return "redirect:/";
}
private void addUserAttributes(Model model) {
Subject currentUser = SecurityUtils.getSubject();
String permission = "";
if (currentUser.hasRole("ADMIN")) {
model.addAttribute("role", "ADMIN");
} else if (currentUser.hasRole("USER")) {
model.addAttribute("role", "USER");
}
if (currentUser.isPermitted("READ")) {
permission = permission + " READ";
}
if (currentUser.isPermitted("WRITE")) {
permission = permission + " WRITE";
}
model.addAttribute("username", currentUser.getPrincipal());
model.addAttribute("permission", permission);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/apache-shiro/src/main/java/com/baeldung/comparison/shiro/models/UserCredentials.java | security-modules/apache-shiro/src/main/java/com/baeldung/comparison/shiro/models/UserCredentials.java | package com.baeldung.comparison.shiro.models;
public class UserCredentials {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "username = " + getUsername();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/apache-shiro/src/main/java/com/baeldung/comparison/springsecurity/Application.java | security-modules/apache-shiro/src/main/java/com/baeldung/comparison/springsecurity/Application.java | package com.baeldung.comparison.springsecurity;
import org.apache.shiro.spring.boot.autoconfigure.ShiroAnnotationProcessorAutoConfiguration;
import org.apache.shiro.spring.boot.autoconfigure.ShiroAutoConfiguration;
import org.apache.shiro.spring.config.web.autoconfigure.ShiroWebAutoConfiguration;
import org.apache.shiro.spring.config.web.autoconfigure.ShiroWebFilterConfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication(exclude = {ShiroAutoConfiguration.class,
ShiroAnnotationProcessorAutoConfiguration.class,
ShiroWebAutoConfiguration.class,
ShiroWebFilterConfiguration.class})
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/apache-shiro/src/main/java/com/baeldung/comparison/springsecurity/config/SecurityConfig.java | security-modules/apache-shiro/src/main/java/com/baeldung/comparison/springsecurity/config/SecurityConfig.java | package com.baeldung.comparison.springsecurity.config;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.csrf()
.disable()
.authorizeRequests(authorize -> authorize.antMatchers("/index", "/login")
.permitAll()
.antMatchers("/home", "/logout")
.authenticated()
.antMatchers("/admin/**")
.hasRole("ADMIN"))
.formLogin(formLogin -> formLogin.loginPage("/login")
.failureUrl("/login-error"));
return http.build();
}
@Bean
public InMemoryUserDetailsManager userDetailsService() throws Exception {
UserDetails jerry = User.withUsername("Jerry")
.password(passwordEncoder().encode("password"))
.authorities("READ", "WRITE")
.roles("ADMIN")
.build();
UserDetails tom = User.withUsername("Tom")
.password(passwordEncoder().encode("password"))
.authorities("READ")
.roles("USER")
.build();
return new InMemoryUserDetailsManager(jerry, tom);
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/apache-shiro/src/main/java/com/baeldung/comparison/springsecurity/web/SpringController.java | security-modules/apache-shiro/src/main/java/com/baeldung/comparison/springsecurity/web/SpringController.java | package com.baeldung.comparison.springsecurity.web;
import java.util.Collection;
import javax.servlet.http.HttpServletRequest;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class SpringController {
@GetMapping("/")
public String getIndex() {
return "comparison/index";
}
@GetMapping("/login")
public String showLoginPage() {
return "comparison/login";
}
@RequestMapping("/login-error")
public String loginError(Model model) {
model.addAttribute("error", "Invalid Credentials");
return "comparison/login";
}
@PostMapping("/login")
public String doLogin(HttpServletRequest req) {
return "redirect:/home";
}
@GetMapping("/home")
public String showHomePage(HttpServletRequest req, Model model) {
addUserAttributes(model);
return "comparison/home";
}
@GetMapping("/admin")
public String adminOnly(HttpServletRequest req, Model model) {
addUserAttributes(model);
model.addAttribute("adminContent", "only admin can view this");
return "comparison/home";
}
private void addUserAttributes(Model model) {
Authentication auth = SecurityContextHolder.getContext()
.getAuthentication();
if (auth != null && !auth.getClass()
.equals(AnonymousAuthenticationToken.class)) {
User user = (User) auth.getPrincipal();
model.addAttribute("username", user.getUsername());
Collection<GrantedAuthority> authorities = user.getAuthorities();
for (GrantedAuthority authority : authorities) {
if (authority.getAuthority()
.contains("USER")) {
model.addAttribute("role", "USER");
model.addAttribute("permission", "READ");
} else if (authority.getAuthority()
.contains("ADMIN")) {
model.addAttribute("role", "ADMIN");
model.addAttribute("permission", "READ WRITE");
}
}
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/apache-shiro/src/main/java/com/baeldung/permissions/custom/PathPermission.java | security-modules/apache-shiro/src/main/java/com/baeldung/permissions/custom/PathPermission.java | package com.baeldung.permissions.custom;
import org.apache.shiro.authz.Permission;
import java.nio.file.Path;
public class PathPermission implements Permission {
private final Path path;
public PathPermission(Path path) {
this.path = path;
}
@Override
public boolean implies(Permission p) {
if(p instanceof PathPermission) {
return ((PathPermission) p).path.startsWith(path);
}
return false;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/apache-shiro/src/main/java/com/baeldung/permissions/custom/PathPermissionResolver.java | security-modules/apache-shiro/src/main/java/com/baeldung/permissions/custom/PathPermissionResolver.java | package com.baeldung.permissions.custom;
import org.apache.shiro.authz.Permission;
import org.apache.shiro.authz.permission.PermissionResolver;
import java.nio.file.Paths;
public class PathPermissionResolver implements PermissionResolver {
@Override
public Permission resolvePermission(String permissionString) {
return new PathPermission(Paths.get(permissionString));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/apache-shiro/src/main/java/com/baeldung/permissions/custom/Main.java | security-modules/apache-shiro/src/main/java/com/baeldung/permissions/custom/Main.java | package com.baeldung.permissions.custom;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.Ini;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.text.IniRealm;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Main {
private static final transient Logger log = LoggerFactory.getLogger(Main.class);
public static void main(String[] args) {
IniRealm realm = new IniRealm();
Ini ini = Ini.fromResourcePath(Main.class.getResource("/com/baeldung/shiro/permissions/custom/shiro.ini").getPath());
realm.setIni(ini);
realm.setPermissionResolver(new PathPermissionResolver());
realm.init();
SecurityManager securityManager = new DefaultSecurityManager(realm);
SecurityUtils.setSecurityManager(securityManager);
Subject currentUser = SecurityUtils.getSubject();
if (!currentUser.isAuthenticated()) {
UsernamePasswordToken token = new UsernamePasswordToken("paul.reader", "password4");
token.setRememberMe(true);
try {
currentUser.login(token);
} catch (UnknownAccountException uae) {
log.error("Username Not Found!", uae);
} catch (IncorrectCredentialsException ice) {
log.error("Invalid Credentials!", ice);
} catch (LockedAccountException lae) {
log.error("Your Account is Locked!", lae);
} catch (AuthenticationException ae) {
log.error("Unexpected Error!", ae);
}
}
log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");
if (currentUser.hasRole("admin")) {
log.info("Welcome Admin");
} else if(currentUser.hasRole("editor")) {
log.info("Welcome, Editor!");
} else if(currentUser.hasRole("author")) {
log.info("Welcome, Author");
} else {
log.info("Welcome, Guest");
}
if(currentUser.isPermitted("/articles/drafts/new-article")) {
log.info("You can access articles");
} else {
log.info("You cannot access articles!");
}
currentUser.logout();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/apache-shiro/src/main/java/com/baeldung/intro/MyCustomRealm.java | security-modules/apache-shiro/src/main/java/com/baeldung/intro/MyCustomRealm.java | package com.baeldung.intro;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.jdbc.JdbcRealm;
import org.apache.shiro.subject.PrincipalCollection;
public class MyCustomRealm extends JdbcRealm {
private Map<String, String> credentials = new HashMap<>();
private Map<String, Set<String>> roles = new HashMap<>();
private Map<String, Set<String>> perm = new HashMap<>();
{
credentials.put("user", "password");
credentials.put("user2", "password2");
credentials.put("user3", "password3");
roles.put("user", new HashSet<>(Arrays.asList("admin")));
roles.put("user2", new HashSet<>(Arrays.asList("editor")));
roles.put("user3", new HashSet<>(Arrays.asList("author")));
perm.put("admin", new HashSet<>(Arrays.asList("*")));
perm.put("editor", new HashSet<>(Arrays.asList("articles:*")));
perm.put("author",
new HashSet<>(Arrays.asList("articles:compose",
"articles:save")));
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
throws AuthenticationException {
UsernamePasswordToken uToken = (UsernamePasswordToken) token;
if(uToken.getUsername() == null
|| uToken.getUsername().isEmpty()
|| !credentials.containsKey(uToken.getUsername())
) {
throw new UnknownAccountException("username not found!");
}
return new SimpleAuthenticationInfo(
uToken.getUsername(), credentials.get(uToken.getUsername()),
getName());
}
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
Set<String> roleNames = new HashSet<>();
Set<String> permissions = new HashSet<>();
principals.forEach(p -> {
try {
Set<String> roles = getRoleNamesForUser(null, (String) p);
roleNames.addAll(roles);
permissions.addAll(getPermissions(null, null,roles));
} catch (SQLException e) {
e.printStackTrace();
}
});
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roleNames);
info.setStringPermissions(permissions);
return info;
}
@Override
protected Set<String> getRoleNamesForUser(Connection conn, String username) throws SQLException {
if(!roles.containsKey(username)) {
throw new SQLException("username not found!");
}
return roles.get(username);
}
@Override
protected Set<String> getPermissions(Connection conn, String username, Collection<String> roleNames) throws SQLException {
for (String role : roleNames) {
if (!perm.containsKey(role)) {
throw new SQLException("role not found!");
}
}
Set<String> finalSet = new HashSet<>();
for (String role : roleNames) {
finalSet.addAll(perm.get(role));
}
return finalSet;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/apache-shiro/src/main/java/com/baeldung/intro/Main.java | security-modules/apache-shiro/src/main/java/com/baeldung/intro/Main.java | package com.baeldung.intro;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Main {
private static final transient Logger log = LoggerFactory.getLogger(Main.class);
public static void main(String[] args) {
Realm realm = new MyCustomRealm();
SecurityManager securityManager = new DefaultSecurityManager(realm);
SecurityUtils.setSecurityManager(securityManager);
Subject currentUser = SecurityUtils.getSubject();
if (!currentUser.isAuthenticated()) {
UsernamePasswordToken token
= new UsernamePasswordToken("user", "password");
token.setRememberMe(true);
try {
currentUser.login(token);
} catch (UnknownAccountException uae) {
log.error("Username Not Found!", uae);
} catch (IncorrectCredentialsException ice) {
log.error("Invalid Credentials!", ice);
} catch (LockedAccountException lae) {
log.error("Your Account is Locked!", lae);
} catch (AuthenticationException ae) {
log.error("Unexpected Error!", ae);
}
}
log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");
if (currentUser.hasRole("admin")) {
log.info("Welcome Admin");
} else if(currentUser.hasRole("editor")) {
log.info("Welcome, Editor!");
} else if(currentUser.hasRole("author")) {
log.info("Welcome, Author");
} else {
log.info("Welcome, Guest");
}
if(currentUser.isPermitted("articles:compose")) {
log.info("You can compose an article");
} else {
log.info("You are not permitted to compose an article!");
}
if(currentUser.isPermitted("articles:save")) {
log.info("You can save articles");
} else {
log.info("You can not save articles");
}
if(currentUser.isPermitted("articles:publish")) {
log.info("You can publish articles");
} else {
log.info("You can not publish articles");
}
Session session = currentUser.getSession();
session.setAttribute("key", "value");
String value = (String) session.getAttribute("key");
if (value.equals("value")) {
log.info("Retrieved the correct value! [" + value + "]");
}
currentUser.logout();
System.exit(0);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/apache-shiro/src/main/java/com/baeldung/intro/ShiroSpringApplication.java | security-modules/apache-shiro/src/main/java/com/baeldung/intro/ShiroSpringApplication.java | package com.baeldung.intro;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.context.annotation.Bean;
/**
* Created by smatt on 21/08/2017.
*/
@SpringBootApplication(exclude = SecurityAutoConfiguration.class)
public class ShiroSpringApplication {
private static final transient Logger log = LoggerFactory.getLogger(ShiroSpringApplication.class);
public static void main(String... args) {
SpringApplication.run(ShiroSpringApplication.class, args);
}
@Bean
public Realm realm() {
return new MyCustomRealm();
}
@Bean
public ShiroFilterChainDefinition filterChainDefinition() {
DefaultShiroFilterChainDefinition filter
= new DefaultShiroFilterChainDefinition();
filter.addPathDefinition("/secure", "authc");
filter.addPathDefinition("/**", "anon");
return filter;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/apache-shiro/src/main/java/com/baeldung/intro/controllers/ShiroSpringController.java | security-modules/apache-shiro/src/main/java/com/baeldung/intro/controllers/ShiroSpringController.java | package com.baeldung.intro.controllers;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.baeldung.intro.models.UserCredentials;
import javax.servlet.http.HttpServletRequest;
@Controller
public class ShiroSpringController {
@GetMapping("/")
public String index() {
return "index";
}
@RequestMapping( value = "/login", method = {RequestMethod.GET, RequestMethod.POST})
public String login(HttpServletRequest req, UserCredentials cred, RedirectAttributes attr) {
if(req.getMethod().equals(RequestMethod.GET.toString())) {
return "login";
} else {
Subject subject = SecurityUtils.getSubject();
if(!subject.isAuthenticated()) {
UsernamePasswordToken token = new UsernamePasswordToken(
cred.getUsername(), cred.getPassword(), cred.isRememberMe());
try {
subject.login(token);
} catch (AuthenticationException ae) {
ae.printStackTrace();
attr.addFlashAttribute("error", "Invalid Credentials");
return "redirect:/login";
}
}
return "redirect:/secure";
}
}
@GetMapping("/secure")
public String secure(ModelMap modelMap) {
Subject currentUser = SecurityUtils.getSubject();
String role = "", permission = "";
if(currentUser.hasRole("admin")) {
role = role + "You are an Admin";
}
else if(currentUser.hasRole("editor")) {
role = role + "You are an Editor";
}
else if(currentUser.hasRole("author")) {
role = role + "You are an Author";
}
if(currentUser.isPermitted("articles:compose")) {
permission = permission + "You can compose an article, ";
} else {
permission = permission + "You are not permitted to compose an article!, ";
}
if(currentUser.isPermitted("articles:save")) {
permission = permission + "You can save articles, ";
} else {
permission = permission + "\nYou can not save articles, ";
}
if(currentUser.isPermitted("articles:publish")) {
permission = permission + "\nYou can publish articles";
} else {
permission = permission + "\nYou can not publish articles";
}
modelMap.addAttribute("username", currentUser.getPrincipal());
modelMap.addAttribute("permission", permission);
modelMap.addAttribute("role", role);
return "secure";
}
@PostMapping("/logout")
public String logout() {
Subject subject = SecurityUtils.getSubject();
subject.logout();
return "redirect:/";
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/apache-shiro/src/main/java/com/baeldung/intro/models/UserCredentials.java | security-modules/apache-shiro/src/main/java/com/baeldung/intro/models/UserCredentials.java | package com.baeldung.intro.models;
public class UserCredentials {
private String username;
private String password;
private boolean rememberMe = false;
public UserCredentials() {}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean isRememberMe() {
return rememberMe;
}
public void setRememberMe(boolean rememberMe) {
this.rememberMe = rememberMe;
}
@Override
public String toString() {
return "username = " + getUsername()
+ "\nrememberMe = " + isRememberMe();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/jjwt/src/test/java/io/jsonwebtoken/jjwtfun/DemoApplicationIntegrationTest.java | security-modules/jjwt/src/test/java/io/jsonwebtoken/jjwtfun/DemoApplicationIntegrationTest.java | package io.jsonwebtoken.jjwtfun;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = JJWTFunApplication.class)
@WebAppConfiguration
public class DemoApplicationIntegrationTest {
@Test
public void contextLoads() {
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/jjwt/src/test/java/io/jsonwebtoken/jjwtfun/util/JWTDecoderUtilUnitTest.java | security-modules/jjwt/src/test/java/io/jsonwebtoken/jjwtfun/util/JWTDecoderUtilUnitTest.java | package io.jsonwebtoken.jjwtfun.util;
import io.jsonwebtoken.SignatureAlgorithm;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.jupiter.api.Assertions.assertTrue;
class JWTDecoderUtilUnitTest {
private final static String SIMPLE_TOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkJhZWxkdW5nIFVzZXIiLCJpYXQiOjE1MTYyMzkwMjJ9";
private final static String SIGNED_TOKEN = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkJhZWxkdW5nIFVzZXIiLCJpYXQiOjE1MTYyMzkwMjJ9.6h_QYBTbyKxfMq3TGiAhVI416rctV0c0SpzWxVm-0-Y";
@Test
void givenSimpleToken_whenDecoding_thenStringOfHeaderPayloadAreReturned() {
assertThat(JWTDecoderUtil.decodeJWTToken(SIMPLE_TOKEN))
.contains(SignatureAlgorithm.HS256.getValue());
}
@Test
void givenSignedToken_whenDecodingWithInvalidSecret_thenIntegrityIsNotValidated() {
assertThatThrownBy(() -> JWTDecoderUtil.
isTokenValid(SIGNED_TOKEN, "BAD_SECRET"))
.hasMessage("Could not verify JWT token integrity!");
}
@Test
void givenSignedToken_whenDecodingWithValidSecret_thenIntegrityIsValidated() throws Exception {
assertTrue(JWTDecoderUtil.isTokenValid(SIGNED_TOKEN, "randomSecretWithSome!!CharacterS!"));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/JJWTFunApplication.java | security-modules/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/JJWTFunApplication.java | package io.jsonwebtoken.jjwtfun;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class JJWTFunApplication {
public static void main(String[] args) {
SpringApplication.run(JJWTFunApplication.class, args);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/DynamicJWTController.java | security-modules/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/DynamicJWTController.java | package io.jsonwebtoken.jjwtfun.controller;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.impl.compression.DeflateCompressionAlgorithm;
import io.jsonwebtoken.jjwtfun.model.JwtResponse;
import io.jsonwebtoken.jjwtfun.service.SecretService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.UnsupportedEncodingException;
import java.time.Instant;
import java.util.Date;
import java.util.Map;
import static org.springframework.web.bind.annotation.RequestMethod.POST;
@RestController
public class DynamicJWTController extends BaseController {
@Autowired
SecretService secretService;
@RequestMapping(value = "/dynamic-builder-general", method = POST)
public JwtResponse dynamicBuilderGeneric(@RequestBody Map<String, Object> claims) throws UnsupportedEncodingException {
String jws = Jwts.builder()
.setClaims(claims)
.signWith(SignatureAlgorithm.HS256, secretService.getHS256SecretBytes())
.compact();
return new JwtResponse(jws);
}
@RequestMapping(value = "/dynamic-builder-compress", method = POST)
public JwtResponse dynamicBuildercompress(@RequestBody Map<String, Object> claims) throws UnsupportedEncodingException {
String jws = Jwts.builder()
.setClaims(claims)
.compressWith(new DeflateCompressionAlgorithm())
.signWith(SignatureAlgorithm.HS256, secretService.getHS256SecretBytes())
.compact();
return new JwtResponse(jws);
}
@RequestMapping(value = "/dynamic-builder-specific", method = POST)
public JwtResponse dynamicBuilderSpecific(@RequestBody Map<String, Object> claims) throws UnsupportedEncodingException {
JwtBuilder builder = Jwts.builder();
claims.forEach((key, value) -> {
switch (key) {
case "iss":
ensureType(key, value, String.class);
builder.setIssuer((String) value);
break;
case "sub":
ensureType(key, value, String.class);
builder.setSubject((String) value);
break;
case "aud":
ensureType(key, value, String.class);
builder.setAudience((String) value);
break;
case "exp":
ensureType(key, value, Long.class);
builder.setExpiration(Date.from(Instant.ofEpochSecond(Long.parseLong(value.toString()))));
break;
case "nbf":
ensureType(key, value, Long.class);
builder.setNotBefore(Date.from(Instant.ofEpochSecond(Long.parseLong(value.toString()))));
break;
case "iat":
ensureType(key, value, Long.class);
builder.setIssuedAt(Date.from(Instant.ofEpochSecond(Long.parseLong(value.toString()))));
break;
case "jti":
ensureType(key, value, String.class);
builder.setId((String) value);
break;
default:
builder.claim(key, value);
}
});
builder.signWith(SignatureAlgorithm.HS256, secretService.getHS256SecretBytes());
return new JwtResponse(builder.compact());
}
private void ensureType(String registeredClaim, Object value, Class expectedType) {
boolean isCorrectType = expectedType.isInstance(value) || expectedType == Long.class && value instanceof Integer;
if (!isCorrectType) {
String msg = "Expected type: " + expectedType.getCanonicalName() + " for registered claim: '" + registeredClaim + "', but got value: " + value + " of type: " + value.getClass()
.getCanonicalName();
throw new JwtException(msg);
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/BaseController.java | security-modules/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/BaseController.java | package io.jsonwebtoken.jjwtfun.controller;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureException;
import io.jsonwebtoken.jjwtfun.model.JwtResponse;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
public class BaseController {
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler({ SignatureException.class, MalformedJwtException.class, JwtException.class })
public JwtResponse exception(Exception e) {
JwtResponse response = new JwtResponse();
response.setStatus(JwtResponse.Status.ERROR);
response.setMessage(e.getMessage());
response.setExceptionType(e.getClass()
.getName());
return response;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/FormController.java | security-modules/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/FormController.java | package io.jsonwebtoken.jjwtfun.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;
@Controller
public class FormController {
@RequestMapping(value = "/jwt-csrf-form", method = GET)
public String csrfFormGet() {
return "jwt-csrf-form";
}
@RequestMapping(value = "/jwt-csrf-form", method = POST)
public String csrfFormPost(@RequestParam(name = "_csrf") String csrf, Model model) {
model.addAttribute("csrf", csrf);
return "jwt-csrf-form-result";
}
@RequestMapping("/expired-jwt")
public String expiredJwt() {
return "expired-jwt";
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/SecretsController.java | security-modules/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/SecretsController.java | package io.jsonwebtoken.jjwtfun.controller;
import io.jsonwebtoken.jjwtfun.service.SecretService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;
@RestController
public class SecretsController extends BaseController {
@Autowired
SecretService secretService;
@RequestMapping(value = "/get-secrets", method = GET)
public Map<String, String> getSecrets() {
return secretService.getSecrets();
}
@RequestMapping(value = "/refresh-secrets", method = GET)
public Map<String, String> refreshSecrets() throws NoSuchAlgorithmException {
return secretService.refreshSecrets();
}
@RequestMapping(value = "/set-secrets", method = POST)
public Map<String, String> setSecrets(@RequestBody Map<String, String> secrets) {
secretService.setSecrets(secrets);
return secretService.getSecrets();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/HomeController.java | security-modules/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/HomeController.java | package io.jsonwebtoken.jjwtfun.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
@RestController
public class HomeController {
@RequestMapping("/")
public String home(HttpServletRequest req) {
String requestUrl = getUrl(req);
return "Available commands (assumes httpie - https://github.com/jkbrzt/httpie):\n\n" + " http " + requestUrl + "/\n\tThis usage message\n\n" + " http " + requestUrl + "/static-builder\n\tbuild JWT from hardcoded claims\n\n" + " http POST "
+ requestUrl + "/dynamic-builder-general claim-1=value-1 ... [claim-n=value-n]\n\tbuild JWT from passed in claims (using general claims map)\n\n" + " http POST " + requestUrl
+ "/dynamic-builder-specific claim-1=value-1 ... [claim-n=value-n]\n\tbuild JWT from passed in claims (using specific claims methods)\n\n" + " http POST " + requestUrl
+ "/dynamic-builder-compress claim-1=value-1 ... [claim-n=value-n]\n\tbuild DEFLATE compressed JWT from passed in claims\n\n" + " http " + requestUrl + "/parser?jwt=<jwt>\n\tParse passed in JWT\n\n" + " http " + requestUrl
+ "/parser-enforce?jwt=<jwt>\n\tParse passed in JWT enforcing the 'iss' registered claim and the 'hasMotorcycle' custom claim\n\n" + " http " + requestUrl + "/get-secrets\n\tShow the signing keys currently in use.\n\n" + " http " + requestUrl
+ "/refresh-secrets\n\tGenerate new signing keys and show them.\n\n" + " http POST " + requestUrl
+ "/set-secrets HS256=base64-encoded-value HS384=base64-encoded-value HS512=base64-encoded-value\n\tExplicitly set secrets to use in the application.";
}
private String getUrl(HttpServletRequest req) {
return req.getScheme() + "://" + req.getServerName() + ((req.getServerPort() == 80 || req.getServerPort() == 443) ? "" : ":" + req.getServerPort());
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/StaticJWTController.java | security-modules/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/StaticJWTController.java | package io.jsonwebtoken.jjwtfun.controller;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.jjwtfun.model.JwtResponse;
import io.jsonwebtoken.jjwtfun.service.SecretService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.io.UnsupportedEncodingException;
import java.time.Instant;
import java.util.Date;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
@RestController
public class StaticJWTController extends BaseController {
@Autowired
SecretService secretService;
@RequestMapping(value = "/static-builder", method = GET)
public JwtResponse fixedBuilder() throws UnsupportedEncodingException {
String jws = Jwts.builder()
.setIssuer("Stormpath")
.setSubject("msilverman")
.claim("name", "Micah Silverman")
.claim("scope", "admins")
.setIssuedAt(Date.from(Instant.ofEpochSecond(1466796822L))) // Fri Jun 24 2016 15:33:42 GMT-0400 (EDT)
.setExpiration(Date.from(Instant.ofEpochSecond(4622470422L))) // Sat Jun 24 2116 15:33:42 GMT-0400 (EDT)
.signWith(SignatureAlgorithm.HS256, secretService.getHS256SecretBytes())
.compact();
return new JwtResponse(jws);
}
@RequestMapping(value = "/parser", method = GET)
public JwtResponse parser(@RequestParam String jwt) throws UnsupportedEncodingException {
Jws<Claims> jws = Jwts.parser()
.setSigningKeyResolver(secretService.getSigningKeyResolver()).build()
.parseClaimsJws(jwt);
return new JwtResponse(jws);
}
@RequestMapping(value = "/parser-enforce", method = GET)
public JwtResponse parserEnforce(@RequestParam String jwt) throws UnsupportedEncodingException {
Jws<Claims> jws = Jwts.parser()
.requireIssuer("Stormpath")
.require("hasMotorcycle", true)
.setSigningKeyResolver(secretService.getSigningKeyResolver()).build()
.parseClaimsJws(jwt);
return new JwtResponse(jws);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/util/JWTDecoderUtil.java | security-modules/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/util/JWTDecoderUtil.java | package io.jsonwebtoken.jjwtfun.util;
import io.jsonwebtoken.Jwt;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class JWTDecoderUtil {
public static String decodeJWTToken(String token) {
Base64.Decoder decoder = Base64.getUrlDecoder();
String[] chunks = token.split("\\.");
String header = new String(decoder.decode(chunks[0]));
String payload = new String(decoder.decode(chunks[1]));
return header + " " + payload;
}
public static boolean isTokenValid(String token, String secretKey) throws Exception {
SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(), SignatureAlgorithm.HS256.getJcaName());
JwtParser jwtParser = Jwts.parser()
.verifyWith(secretKeySpec)
.build();
try {
jwtParser.parse(token);
} catch (Exception e) {
throw new Exception("Could not verify JWT token integrity!", e);
}
return true;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/service/SecretService.java | security-modules/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/service/SecretService.java | package io.jsonwebtoken.jjwtfun.service;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwsHeader;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.SigningKeyResolver;
import io.jsonwebtoken.SigningKeyResolverAdapter;
import io.jsonwebtoken.impl.TextCodec;
import io.jsonwebtoken.lang.Assert;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
@Service
public class SecretService {
private Map<String, String> secrets = new HashMap<>();
private SigningKeyResolver signingKeyResolver = new SigningKeyResolverAdapter() {
@Override
public byte[] resolveSigningKeyBytes(JwsHeader header, Claims claims) {
return TextCodec.BASE64.decode(secrets.get(header.getAlgorithm()));
}
};
@PostConstruct
public void setup() throws NoSuchAlgorithmException {
refreshSecrets();
}
public SigningKeyResolver getSigningKeyResolver() {
return signingKeyResolver;
}
public Map<String, String> getSecrets() {
return secrets;
}
public void setSecrets(Map<String, String> secrets) {
Assert.notNull(secrets);
Assert.hasText(secrets.get(SignatureAlgorithm.HS256.getJcaName()));
Assert.hasText(secrets.get(SignatureAlgorithm.HS384.getJcaName()));
Assert.hasText(secrets.get(SignatureAlgorithm.HS512.getJcaName()));
this.secrets = secrets;
}
public byte[] getHS256SecretBytes() {
return TextCodec.BASE64.decode(secrets.get(SignatureAlgorithm.HS256.getJcaName()));
}
public byte[] getHS384SecretBytes() {
return TextCodec.BASE64.decode(secrets.get(SignatureAlgorithm.HS384.getJcaName()));
}
public byte[] getHS512SecretBytes() {
return TextCodec.BASE64.decode(secrets.get(SignatureAlgorithm.HS512.getJcaName()));
}
public Map<String, String> refreshSecrets() throws NoSuchAlgorithmException {
SecretKey key = KeyGenerator.getInstance(SignatureAlgorithm.HS256.getJcaName()).generateKey();
secrets.put(SignatureAlgorithm.HS256.getJcaName(), TextCodec.BASE64.encode(key.getEncoded()));
key = KeyGenerator.getInstance(SignatureAlgorithm.HS384.getJcaName()).generateKey();
secrets.put(SignatureAlgorithm.HS384.getJcaName(), TextCodec.BASE64.encode(key.getEncoded()));
key = KeyGenerator.getInstance(SignatureAlgorithm.HS512.getJcaName()).generateKey();
secrets.put(SignatureAlgorithm.HS512.getJcaName(), TextCodec.BASE64.encode(key.getEncoded()));
return secrets;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/model/JwtResponse.java | security-modules/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/model/JwtResponse.java | package io.jsonwebtoken.jjwtfun.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
@JsonInclude(JsonInclude.Include.NON_NULL)
public class JwtResponse {
private String message;
private Status status;
private String exceptionType;
private String jwt;
private Jws<Claims> jws;
public enum Status {
SUCCESS, ERROR
}
public JwtResponse() {
}
public JwtResponse(String jwt) {
this.jwt = jwt;
this.status = Status.SUCCESS;
}
public JwtResponse(Jws<Claims> jws) {
this.jws = jws;
this.status = Status.SUCCESS;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public String getExceptionType() {
return exceptionType;
}
public void setExceptionType(String exceptionType) {
this.exceptionType = exceptionType;
}
public String getJwt() {
return jwt;
}
public void setJwt(String jwt) {
this.jwt = jwt;
}
public Jws<Claims> getJws() {
return jws;
}
public void setJws(Jws<Claims> jws) {
this.jws = jws;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/config/CSRFConfig.java | security-modules/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/config/CSRFConfig.java | package io.jsonwebtoken.jjwtfun.config;
import io.jsonwebtoken.jjwtfun.service.SecretService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.web.csrf.CsrfTokenRepository;
@Configuration
public class CSRFConfig {
@Autowired
SecretService secretService;
@Bean
@ConditionalOnMissingBean
public CsrfTokenRepository jwtCsrfTokenRepository() {
return new JWTCsrfTokenRepository(secretService.getHS256SecretBytes());
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.