Get user roles from Keycloak in Spring/Jhipster

I faced a problem when I tried to use user roles on JHipster 5.x to limit access or filter results; Keycloak returns a token that includes user roles but under wrong path! Keycloak put user roles at realm_access.roles while Spring Security check roles at root of token playload.

I solve this issue in Keycloak and add user roles in roles of playload; Here I want share it with you.

Keycloak essential endpoint

Keycloak is one of great identity server that exist. It's opensource, and free also, by the way if you need professional support you can achieve that from Redhat.
In the Microservice paradigm, we split each business into a service, and one of important business is user management. Keycloack handle it for your system and also help your service to be secure.
Now I want share some common endpoint of Keycloak, to make your job easier.

How we sent a SMS

Once upon a time in the first company that I start my job as Java Developer, I got a task, Send SMS to our clients. Greate! I think it was Java 5 or 6 I'm not sure about it, but I'm sure our SMS provider used legacy methods to get SMS from us; I got this source from Mr. Majidi (one of kind person of that company, and also head of another team of it), and now I decide to share it here for you, may someday help somebody:


public class SMS {
    public static void sendSms(String mobile, String msg) throws Exception {
        String url = "{SERVER_URL}";
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection)obj.openConnection();
        con.setRequestProperty("User-Agent", "Mozilla/5.0");
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
        con.setRequestProperty("accept-charset", "UTF-8");
        String urlParam =
                "HEADER={YOUR_SMS_NUMBER}&DESTINATION=" + "{COUNTRY_CODE}" + mobile.substring(1) +
                        "&MESSAGEID=1&MESSAGE=" + msg + "&DCS=8";
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        BufferedWriter writer =
                new BufferedWriter(new OutputStreamWriter(wr, "UTF-8"));
        int responseCode = con.getResponseCode();
        BufferedReader in =
                new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {

Generate a file for Download in Spring

I need to generate a file for download for a user, imagine, you should give a serial number as a text file to your user. After searching I achieve this solution that works perfectly:

@GetMapping(path = "/file/get", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
public ResponseEntity verificationFile() {
 HttpHeaders headers = new HttpHeaders();
    headers.setContentDispositionFormData("attachment", "test.txt");
 InputStreamResource inputStreamResource = new InputStreamResource(new ByteArrayInputStream("Hello File".getBytes(StandardCharsets.UTF_8)));
 return ResponseEntity.ok().headers(headers).body(inputStreamResource);
After calling http://{SERVER-ADDRESS}:{PORT}/file/get, a file with name test.txt that contains Hello File, geting download.

Filter search result of Elasticsearch to only show user data in JHipster

When we generate a project by JHipster, it doesn't manage that users only access to their data. By default, a user can see all data of an entity (You can find a solution by simple google it).
But after we add Elasticsearch to handle our search, we get a new problem. if user search, he can see result from all data that exists otherwise every user must see their data, not more! by default, the search method is something like this that makes a problem:

    .spliterator(), false).collect(Collectors.toList());

And we have to change it to this one to fix the problem: 

BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery().must(queryStringQuery(query));
if (SecurityUtils.isAuthenticated() && !SecurityUtils.isCurrentUserInRole(AuthoritiesConstants.ADMIN)) {
 queryBuilder = queryBuilder.filter(matchQuery("user.login", SecurityUtils.getCurrentUserLogin().orElse("")));
return, false).collect(Collectors.toList());

In that code, we check if the user doesn't have Admin role (), then we add another filter to quryBuilder to limit the search for the current user.
The solution exists at the 21-point sample project on GitHub that I use it for the source of this post (

Lombok, Hibernate, and 'StackOverflowError: null' Exception!

I really like Project Lombok, with use of this library you can code cleaner, just look at the sample of  @Data (here) and you give me the right!
But after using @Data on an entity, and use it into another entity (eg a Set of comments of a post), throw an ugly error: java.lang.StackOverflowError: null. @Data is a shortcut for these annotations of Lombok:
  • @Getter
  • @Setter
  • @ToString
  • @RequiredArgsConstructor
  • @EqualsAndHashCode
And @EqualsAndHashCode makes this error! I found the solution at last comment of this question on StackOverflow: We should add this line just after at @Data and exclude relational fields from Equals and Hash methods:
I used it on my project, Feader, and you can use it as a sample to check it out ( on develop branch); These are my use case classes, and, FeedEntry use into Feed (like comments and post):
package com.glinboy.feader.model;

import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.Lob;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;

import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;

import lombok.Data;
import lombok.EqualsAndHashCode;

@EqualsAndHashCode(callSuper=true, exclude="entries")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Feed extends BaseModel {

 private static final long serialVersionUID = 7720285113632455831L;
 private String title;
    private String link;
    private String description;
      joinColumns = @JoinColumn(name = "feed_id", nullable=false),
            inverseJoinColumns = @JoinColumn(name = "category_id", nullable=false))
    private Set category;

    private Set entries;

package com.glinboy.feader.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;

import lombok.Data;
import lombok.EqualsAndHashCode;

@EqualsAndHashCode(callSuper=true, exclude="feed")
public class FeedEntry extends BaseModel {

 private static final long serialVersionUID = -7086809764656937022L;
 private String title;
 private String description;
 private String link;
 private String author;
 private String guid;
 @JoinColumn(name="feed_id", nullable=false)
 private Feed feed;

Hello World!

Let's start with popular programmer style!
As a Java Developer:

class Main {
  public static void main(String[] args) {
    System.out.println("Hello world!");
As a C++ Programmer:

#include <iostream>
using namespace std;

int main() 
    cout << "Hello, World!";
    return 0;
As a Python Developer:

print 'hello world!'
As a fan of Rust:

fn main() {
    println!("Hello World!");
As a fan of Go:

package main

import "fmt"

func main() {
 fmt.Println("Hello World!")
As a fan of Elixir:

IO.puts "Hello, World!"
And Other my friends:

  "from": "GLinBoy",
  "to": [
  "message": "Hello World!"