Keycloak AuthenticationFlowContext return always http protocol - keycloak

I'm implementing Authenticator class and use AuthenticationFlowContext. When I refer to the server via HTTPS, in context.getUriInfo().getAbsolutePath() still leaves http://{hostname}/auth/... .
public void authenticate(AuthenticationFlowContext context) {
String url = context.getUriInfo().getAbsolutePath()+"?client_id="+context.getClientSession().getClient().getClientId()
+"&redirect_uri="+context.getClientSession().getNote("redirect_uri")
+"&state="+context.getClientSession().getNote("state")
+"&response_type="+context.getClientSession().getNote("response_type");
try {
url = URLEncoder.encode(url, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
context.forceChallenge(Response.seeOther(URI.create(idpUrl+"idp/l?lvl=2&url="+url)).build());
}

You must configure keycloak server and nginx:
location / {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-Port 443;
proxy_pass http://localhost:8080;
}
Https is enabled.

Related

Whether Web socket using Stomp and Spring REST API Service can be on same project

I have a Rest API service which will accept all the GET request and also post request in my web application.
#GetMapping
public ResponseEntity<Object> getRequest(HttpServletRequest
request,#RequestHeader Map<String,String> headers){
Object response = null;
*************
*************
}
I also have the web socket using Stomp which is registered with websocket
public void registerStompEndpoints(StompEndpointRegistry registry)
{
registry.addEndpoint("/websocket")
.withSockJS();
}
But when i call from the UI to connect with web socket it is going inside the rest api GET mapping instead of web socket Connection
public connect() {
console.log("Web Socket");
this.socket = new SockJs(`http://localhost:28880/socket/ourwebsocket`,
{ headers : {Authorization : 'Bearer <TOKEN>' }});
this.stompClient = Stomp.over(this.socket);
return this.stompClient;
}

How to configure spring + keycloak + jwt?

I want to permit all post request without jwt.
I have the follow configuration:
#Slf4j
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeRequests().antMatchers(HttpMethod.POST).permitAll();
http.authorizeRequests().antMatchers(HttpMethod.GET).permitAll();
http.oauth2ResourceServer().jwt().and().bearerTokenResolver(this::tokenExtractor);
}
private String tokenExtractor(HttpServletRequest request) {
Cookie cookie = WebUtils.getCookie(request, "access_token");
if (cookie != null) {
log.info("Cookie found");
return cookie.getValue();
}
log.info("Cookie not found");
return null;
}
}
my yaml has:
spring:
security:
oauth2:
resourceserver:
jwt:
issuer-uri: http://kc-server/realms/master
keycloak:
realm: master
resource: auth
auth-server-url: http://url
credentials:
secret: ${KEYCLOAK_SECRET}
when I try to use any POST request I always get 401 error (Bearer error="invalid_token", error_description="An error occurred while attempting to decode the Jwt: Jwt expired at 2022-03-03T15:39:50Z", error_uri="https://tools.ietf.org/html/rfc6750#section-3.1"), but expect 2xx.
What is wrong with my configuration ?

Spring Boot Rest API #CrossOrigin Not working

I know this question asked already but I have the same issue and did not find any solution
Spring Boot, I have Rest API and added a cross-origin annotation
#CrossOrigin(origins = "*", allowedHeaders = "*")
But it still showing me an error
Access to XMLHttpRequest at 'http://localhost:8080/API/findUser' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
ERROR HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: null, ok: false}
I also tried
#Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedMethods("GET", "POST", "PUT", "DELETE").allowedOrigins("*")
.allowedHeaders("*");
}
};
}
But not working
Just in case if somebody found this question after some Googleing, this could potentially solve the issue.
If you are using Spring security. You should enable cors() there as well. Set your WebSecurityConfigurerAdapter like this:
public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception {
http
.cors() //<-- Enables CORS
.and()
.antMatcher("/api/**")
.authorizeRequests()
.anyRequest()
.hasRole("admin")
.and()
.oauth2ResourceServer()
.jwt()
.jwtAuthenticationConverter(new CustomJwtAuthenticationConverter());
}
}

Failed to send mail with SSL=true on port 25 using javax.mail

// Below is my configuration:
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
properties.put("mail.smtp.port", "25");
properties.put("mail.smtp.ssl.enable", "true");
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.socketFactory.fallback", "false");
properties.put("mail.smtp.socketFactory.class",javax.net.ssl.SSLSocketFactory");
Authenticator auth = new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("username", "password");
}
};
Session session = Session.getInstance(properties, auth);
//My port number is 25 and SSL should be true. I am getting below exception:
javax.mail.MessagingException: Exception reading response;
nested exception is:
javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?
at com.sun.mail.smtp.SMTPTransport.readServerResponse(SMTPTransport.java:1090)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:986)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:197)
at javax.mail.Service.connect(Service.java:233)

Unable to disable ssl verification in cURL

I have exposed some ReSTFul web services on a corporate network [ Company's Internal Network]. I am trying to test those using curl on windows. The address of the GET request is something like this --> (https on non standard port)
https://myCompanysNet:13432/something/something/1.0.0/
curl -H "Accept:application/xml" --user username:password "https://myCompanysNet:13432/something/something/1.0.0/"
And I have added option insecure in curlrc conf. file
But instead of getting the required XMLs in the response , the output is some html page showing the following error
HTTPS Request Blocked
Your request has been blocked by because it is not allowed to use HTTP CONNECT method to port 13432. This may be due to the use of a non-standard HTTPS port.
Which is the same error page , when one tries to open restricted websites via company's network !
I have a client code written in java , which works quite fine and fetches the XMLs , but the requirement is to use curl.
EDIT 1 :-
Following method is called in java client code:
static {
disableSslVerification();
}
private static void disableSslVerification() {
try {
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
}
};
// Install the all-trusting trust manager
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
// Create all-trusting host name verifier
HostnameVerifier allHostsValid = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
// Install the all-trusting host verifier
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
}