How to registre user in my own database through keycloak - keycloak

I have been using keycloak for a very short time. made keycloak use my own user database and it works fine.
I would like new users who register to be registered directly in my database. So I implemented the UseRegistrationProvider class which contains the addUser(RealmModel realm, String username) and removeUser(RealmModel realm, UserModel user) methods.
The problem is that in the addUser method I only have the username and I would like to have all the fields that have been filled on the registration form. How do I do?
Thanks

the addUser(...) method return an object implementing the UserModel. You will have to implement a UserModel adapter that enable to set the attributes you want.
See Quickstart example
Regards,

Here is my code. What did i miss?
public class MyUserStorageProvider implements UserStorageProvider,
UserRegistrationProvider,
UserLookupProvider,
UserQueryProvider,
CredentialInputUpdater,
CredentialInputValidator {
private final KeycloakSession session;
private final ComponentModel model;
private final UserRepository repository;
public MyUserStorageProvider(KeycloakSession session, ComponentModel model, UserRepository repository) {
this.session = session;
this.model = model;
this.repository = repository;
}
...
#Override
public UserModel addUser(RealmModel realm, String username) {
User user = new User();
user.setUsername(username);
user.setEmail("I don't have email in addUser method");
if(repository.addUser(user))
return new UserAdapter(session, realm, model, user);
else return null;
}
}
public class UserAdapter extends AbstractUserAdapterFederatedStorage {
private final User user;
private final String keycloakId;
public UserAdapter(KeycloakSession session, RealmModel realm, ComponentModel model, User user) {
super(session, realm, model);
this.user = user;
this.keycloakId = StorageId.keycloakId(model, user.getId());
}
#Override
public String getId() {
return keycloakId;
}
#Override
public String getUsername() {
return user.getUsername();
}
#Override
public void setUsername(String username) {
user.setUsername(username);
}
#Override
public String getEmail() {
return user.getEmail();
}
#Override
public void setEmail(String email) {
user.setEmail(email);
}
#Override
public String getFirstName() {
return user.getFirstName();
}
#Override
public void setFirstName(String firstName) {
user.setFirstName(firstName);
}
#Override
public String getLastName() {
return user.getLastName();
}
#Override
public void setLastName(String lastName) {
user.setLastName(lastName);
}
}
class UserRepository {
private EntityManager em;
public UserRepository(MultivaluedHashMap<String, String> config) {
em = new JpaEntityManagerFactory(new Class[]{User.class}, config).getEntityManager();
}
...
boolean addUser(User user) {
try {
em.getTransaction().begin();
em.persist(user);
em.getTransaction().commit();
return true;
}catch(Exception e) {
return false;
}
}
}

Related

KEYCLOAK - Extending OIDC Protocol | Missing Credentials Tab | Add extra claims in AccessTokenResponse

We are trying to implement SMART On FHIR healthcare authorization protocol specification. This spec is an extension to OIDC (open id connect protocol). In SMART on FHIR, we need to add extra claims called 'patient' with value say '123' in AccessTokenResponse object during the OAUTH dance.
In order to accomplish this, I tried to extended the OIDCLoginProtocol and OIDCLoginProtocolFactory classes and given a new name to this protocol called 'smart-openid-connect'. I created this as a SPI (service provider interface) JAR and copied it to /standalone/deployments folder. Now, I can see the new protocol called 'smart-openid-connect' in the UI, but it does not show Access Type options in the client creation screen to select as a confidential client. Hence, I am not able to create client secrets as the Credentials menu is not appearing for this new protocol.
I have the following questions:
How to enable the Credentials tab in the client creation screen using SPI for the new protocol that I created.?
Which class I need to override to add extra claims in AccessTokenResponse ?
Kindly help me in this regard.
Thanks for your help in advance.
I have followed your steps for developing our custom protocol. When we migrate our company existed authentication protocol, I have used org.keycloak.adapters.authentication.ClientCredentialsProvider, org.keycloak.authentication.ClientAuthenticatorFactory, org.keycloak.authentication.ClientAuthenticator classes for defining our custom protocol. Credentials tab is only visible if oidc and confidential choices are selected. It is defined on UI javascript codes. So we choose oidc option for setting custom protocol. Afterwards, we return back to our custom protocol.
XyzClientAuthenticatorFactory
public class XyzClientAuthenticatorFactory implements ClientAuthenticatorFactory, ClientAuthenticator {
public static final String PROVIDER_ID = "xyz-client-authenticator";
public static final String DISPLAY_TEXT = "Xyz Client Authenticator";
public static final String REFERENCE_CATEGORY = null;
public static final String HELP_TEXT = null;
private static final List<ProviderConfigProperty> configProperties = new ArrayList<ProviderConfigProperty>();
private AuthenticationExecutionModel.Requirement[] REQUIREMENT_CHOICES = {
AuthenticationExecutionModel.Requirement.REQUIRED,
AuthenticationExecutionModel.Requirement.ALTERNATIVE,
AuthenticationExecutionModel.Requirement.DISABLED};
static {
ProviderConfigProperty property;
property = new ProviderConfigProperty();
property.setName(Constants.CLIENT_SETTINGS_APP_ID);
property.setLabel("Xyz App Id");
property.setType(ProviderConfigProperty.STRING_TYPE);
configProperties.add(property);
property = new ProviderConfigProperty();
property.setName(Constants.CLIENT_SETTINGS_APP_KEY);
property.setLabel("Xyz App Key");
property.setType(ProviderConfigProperty.STRING_TYPE);
configProperties.add(property);
}
#Override
public void authenticateClient(ClientAuthenticationFlowContext context) {
}
#Override
public String getDisplayType() {
return DISPLAY_TEXT;
}
#Override
public String getReferenceCategory() {
return REFERENCE_CATEGORY;
}
#Override
public ClientAuthenticator create() {
return this;
}
#Override
public boolean isConfigurable() {
return false;
}
#Override
public AuthenticationExecutionModel.Requirement[] getRequirementChoices() {
return REQUIREMENT_CHOICES;
}
#Override
public boolean isUserSetupAllowed() {
return false;
}
#Override
public List<ProviderConfigProperty> getConfigPropertiesPerClient() {
return configProperties;
}
#Override
public Map<String, Object> getAdapterConfiguration(ClientModel client) {
Map<String, Object> result = new HashMap<>();
result.put(Constants.CLIENT_SETTINGS_APP_ID, client.getAttribute(Constants.CLIENT_SETTINGS_APP_ID));
result.put(Constants.CLIENT_SETTINGS_APP_KEY, client.getAttribute(Constants.CLIENT_SETTINGS_APP_KEY));
return result;
}
#Override
public Set<String> getProtocolAuthenticatorMethods(String loginProtocol) {
if (loginProtocol.equals(OIDCLoginProtocol.LOGIN_PROTOCOL)) {
Set<String> results = new LinkedHashSet<>();
results.add(Constants.CLIENT_SETTINGS_APP_ID);
results.add(Constants.CLIENT_SETTINGS_APP_KEY);
return results;
} else {
return Collections.emptySet();
}
}
#Override
public String getHelpText() {
return HELP_TEXT;
}
#Override
public List<ProviderConfigProperty> getConfigProperties() {
return new LinkedList<>();
}
#Override
public ClientAuthenticator create(KeycloakSession session) {
return this;
}
#Override
public void init(Config.Scope config) {
}
#Override
public void postInit(KeycloakSessionFactory factory) {
}
#Override
public void close() {
}
#Override
public String getId() {
return PROVIDER_ID;
}
}
XyzClientCredential
public class XyzClientCredential implements ClientCredentialsProvider {
public static final String PROVIDER_ID = "xyz-client-credential";
#Override
public String getId() {
return PROVIDER_ID;
}
#Override
public void init(KeycloakDeployment deployment, Object config) {
}
#Override
public void setClientCredentials(KeycloakDeployment deployment, Map<String, String> requestHeaders, Map<String, String> formParams) {
}
}
XyzLoginProtocolFactory
public class XyzLoginProtocolFactory implements LoginProtocolFactory {
static {
}
#Override
public Map<String, ProtocolMapperModel> getBuiltinMappers() {
return new HashMap<>();
}
#Override
public Object createProtocolEndpoint(RealmModel realm, EventBuilder event) {
return new XyzLoginProtocolService(realm, event);
}
protected void addDefaultClientScopes(RealmModel realm, ClientModel newClient) {
addDefaultClientScopes(realm, Arrays.asList(newClient));
}
protected void addDefaultClientScopes(RealmModel realm, List<ClientModel> newClients) {
Set<ClientScopeModel> defaultClientScopes = realm.getDefaultClientScopes(true).stream()
.filter(clientScope -> getId().equals(clientScope.getProtocol()))
.collect(Collectors.toSet());
for (ClientModel newClient : newClients) {
for (ClientScopeModel defaultClientScopeModel : defaultClientScopes) {
newClient.addClientScope(defaultClientScopeModel, true);
}
}
Set<ClientScopeModel> nonDefaultClientScopes = realm.getDefaultClientScopes(false).stream()
.filter(clientScope -> getId().equals(clientScope.getProtocol()))
.collect(Collectors.toSet());
for (ClientModel newClient : newClients) {
for (ClientScopeModel nonDefaultClientScope : nonDefaultClientScopes) {
newClient.addClientScope(nonDefaultClientScope, true);
}
}
}
#Override
public void createDefaultClientScopes(RealmModel newRealm, boolean addScopesToExistingClients) {
// Create default client scopes for realm built-in clients too
if (addScopesToExistingClients) {
addDefaultClientScopes(newRealm, newRealm.getClients());
}
}
#Override
public void setupClientDefaults(ClientRepresentation rep, ClientModel newClient) {
}
#Override
public LoginProtocol create(KeycloakSession session) {
return new XyzLoginProtocol().setSession(session);
}
#Override
public void init(Config.Scope config) {
log.infof("XyzLoginProtocolFactory init");
}
#Override
public void postInit(KeycloakSessionFactory factory) {
factory.register(event -> {
if (event instanceof RealmModel.ClientCreationEvent) {
ClientModel client = ((RealmModel.ClientCreationEvent)event).getCreatedClient();
addDefaultClientScopes(client.getRealm(), client);
addDefaults(client);
}
});
}
protected void addDefaults(ClientModel client) {
}
#Override
public void close() {
}
#Override
public String getId() {
return XyzLoginProtocol.LOGIN_PROTOCOL;
}
}
XyzLoginProtocol
public class XyzLoginProtocol implements LoginProtocol {
public static final String LOGIN_PROTOCOL = "xyz";
protected KeycloakSession session;
protected RealmModel realm;
protected UriInfo uriInfo;
protected HttpHeaders headers;
protected EventBuilder event;
public XyzLoginProtocol(KeycloakSession session, RealmModel realm, UriInfo uriInfo, HttpHeaders headers, EventBuilder event) {
this.session = session;
this.realm = realm;
this.uriInfo = uriInfo;
this.headers = headers;
this.event = event;
}
public XyzLoginProtocol() {
}
#Override
public XyzLoginProtocol setSession(KeycloakSession session) {
this.session = session;
return this;
}
#Override
public XyzLoginProtocol setRealm(RealmModel realm) {
this.realm = realm;
return this;
}
#Override
public XyzLoginProtocol setUriInfo(UriInfo uriInfo) {
this.uriInfo = uriInfo;
return this;
}
#Override
public XyzLoginProtocol setHttpHeaders(HttpHeaders headers) {
this.headers = headers;
return this;
}
#Override
public XyzLoginProtocol setEventBuilder(EventBuilder event) {
this.event = event;
return this;
}
#Override
public Response authenticated(AuthenticationSessionModel authSession, UserSessionModel userSession, ClientSessionContext clientSessionCtx) {
log.debugf("Authenticated.. User: %s, Session Id: %s", userSession.getUser().getUsername(), userSession.getId());
try {
....
} catch (Exception ex) {
// TODO handle TokenNotFoundException exception
log.error(ex.getMessage(), ex);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
}
#Override
public Response sendError(AuthenticationSessionModel authSession, Error error) {
new AuthenticationSessionManager(session).removeAuthenticationSession(realm, authSession, true);
String redirect = authSession.getRedirectUri();
try {
URI uri = new URI(redirect);
return Response.status(302).location(uri).build();
} catch (Exception ex) {
log.error(ex.getMessage(), ex);
return Response.noContent().build();
}
}
#Override
public void backchannelLogout(UserSessionModel userSession, AuthenticatedClientSessionModel clientSession) {
ClientModel client = clientSession.getClient();
new ResourceAdminManager(session).logoutClientSession(realm, client, clientSession);
}
#Override
public Response frontchannelLogout(UserSessionModel userSession, AuthenticatedClientSessionModel clientSession) {
throw new RuntimeException("NOT IMPLEMENTED");
}
#Override
public Response finishLogout(UserSessionModel userSession) {
return Response.noContent().build();
}
#Override
public boolean requireReauthentication(UserSessionModel userSession, AuthenticationSessionModel authSession) {
return false;
}
#Override
public boolean sendPushRevocationPolicyRequest(RealmModel realm, ClientModel resource, int notBefore, String managementUrl) {
PushNotBeforeAction adminAction = new PushNotBeforeAction(TokenIdGenerator.generateId(), Time.currentTime() + 30, resource.getClientId(), notBefore);
String token = session.tokens().encode(adminAction);
log.tracev("pushRevocation resource: {0} url: {1}", resource.getClientId(), managementUrl);
URI target = UriBuilder.fromUri(managementUrl).path(AdapterConstants.K_PUSH_NOT_BEFORE).build();
try {
int status = session.getProvider(HttpClientProvider.class).postText(target.toString(), token);
boolean success = status == 204 || status == 200;
log.tracef("pushRevocation success for %s: %s", managementUrl, success);
return success;
} catch (IOException e) {
ServicesLogger.LOGGER.failedToSendRevocation(e);
return false;
}
}
#Override
public void close() {
}
}
XyzLoginProtocolService
public class XyzLoginProtocolService {
private final RealmModel realm;
private final EventBuilder event;
#Context
private KeycloakSession session;
#Context
private HttpHeaders headers;
#Context
private HttpRequest request;
#Context
private ClientConnection clientConnection;
public XyzLoginProtocolService(RealmModel realm, EventBuilder event) {
this.realm = realm;
this.event = event;
this.event.realm(realm);
}
#POST
#Path("request")
#Produces(MediaType.APPLICATION_JSON)
#NoCache
public Response request(ApipmLoginRequest loginRequest) {
....
}

Spring Security + PostgreSql - How to debug whats going wrong with authentication since there are no error messages?

I am following Spring in action book and creating a small demo application to enhance my spring knowledge.
When i tried to setup spring security with PostgreSQL and tried to test authenticated requests, I am always getting 403 forbidden error with no error messages in console log.
I would like to understand whats wrong with the code.
I tried to add debug level for security, introduced AuthenticationEventListener to monitor the events etc. But none of them tell me why authentication fails.
Register controller working fine and its saving user details to DB with encoded password.
For complete code please look into https://github.com/vin0010/Spring-Recipe
SecurityConfig.java
#Configuration
#EnableWebSecurity(debug = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
DataSource dataSource;
#Autowired
private UserRepository userRepository;
//TODO check why it didn't work
#Autowired
#Qualifier("name")
private UserDetailsService userDetailsService;
#Value("${spring.queries.users-query}")
private String usersQuery;
#Value("${spring.queries.roles-query}")
private String rolesQuery;
#Autowired
public BCryptPasswordEncoder passwordEncoder;
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors().and().csrf().disable()
.authorizeRequests()
.antMatchers("/test").authenticated()
.antMatchers("/register", "/**").permitAll();
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(userDetailsService)
.and()
.jdbcAuthentication()
.usersByUsernameQuery(usersQuery)
.authoritiesByUsernameQuery(rolesQuery)
.dataSource(dataSource)
.passwordEncoder(passwordEncoder);
}
}
TestController for authentication check
#RestController
#RequestMapping("test")
public class TestController {
#GetMapping
public String getDocument(){
return "success";
}
}
Registration controller
#RequestMapping("/register")
public class RegistrationController {
#Autowired
private UserRepository userRepository;
#Autowired
private PasswordEncoder passwordEncoder;
#PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
#ResponseStatus(HttpStatus.ACCEPTED)
public void send(#RequestBody RegistrationForm registrationForm) {
userRepository.save(registrationForm.toUser(passwordEncoder));
}
}
UserRepository.java
public interface UserRepository extends CrudRepository<Users, Long> {
Users findByUsername(String username);
}
UserRepositoryUserDetailsService.java
#Service("name")
public class UserRepositoryUserDetailsService implements UserDetailsService {
#Autowired
private UserRepository userRepository;
#Override
public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
Users users= userRepository.findByUsername(userName);
if (users == null)
throw new UsernameNotFoundException("User '" + userName + "' not found");
return users;
}
}
Users.java
#Entity
#Data
#NoArgsConstructor(access= AccessLevel.PRIVATE, force=true)
#RequiredArgsConstructor
public class Users implements UserDetails {
#Id
#GeneratedValue(strategy= GenerationType.AUTO)
private Long id;
private final String username;
private final String password;
private final boolean enabled;
private final String role;
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return Arrays.asList(new SimpleGrantedAuthority(this.role));
}
#Override
public boolean isAccountNonExpired() {
return true;
}
#Override
public boolean isAccountNonLocked() {
return true;
}
#Override
public boolean isCredentialsNonExpired() {
return true;
}
#Override
public boolean isEnabled() {
return this.enabled;
}
}
queries for user authentication and authorities check
spring.queries.users-query=select username, password, enabled from users where username=?
spring.queries.roles-query=select username, role from users where username=?
Since I created my own User table, I need to get the authentication done via this en entity setup.

Spring Boot - Bean named entityManagerFactory

I am trying to make a simple Spring Boot application generated with jHipster to get from a postgresql a list of articles from a postreSQL database and display it using a rest controller, but when i run it i get
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 0 of constructor in org.adi.security.DomainUserDetailsService required a bean named 'entityManagerFactory' that could not be found.
Action:
Consider defining a bean named 'entityManagerFactory' in your configuration.
But the thing is that that `DomainUserDetailsService is something generated by jhipster which stopped working after i added my classes. So i will write below my classes:
Article Entity:
package org.adi.domain;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="articles")
public class Article implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="article_id")
private int articleId;
#Column(name="title")
private String title;
#Column(name="category")
private String category;
public int getArticleId() {
return articleId;
}
public void setArticleId(int articleId) {
this.articleId = articleId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
}
ArticleDAO (Repository):
#Transactional
#Repository
public class ArticleDAO implements IArticleDAO {
#PersistenceContext
private EntityManager entityManager;
#Override
public Article getArticleById(int articleId) {
return entityManager.find(Article.class, articleId);
}
#SuppressWarnings("unchecked")
#Override
public List<Article> getAllArticles() {
String hql = "FROM Article as atcl ORDER BY atcl.articleId DESC";
return (List<Article>) entityManager.createQuery(hql).getResultList();
}
#Override
public void createArticle(Article article) {
entityManager.persist(article);
}
#Override
public void updateArticle(Article article) {
Article artcl = getArticleById(article.getArticleId());
artcl.setTitle(article.getTitle());
artcl.setCategory(article.getCategory());
entityManager.flush();
}
#Override
public void deleteArticle(int articleId) {
entityManager.remove(getArticleById(articleId));
}
#Override
public boolean articleExists(String title, String category) {
String hql = "FROM Article as atcl WHERE atcl.title = ? and atcl.category = ?";
int count = entityManager.createQuery(hql).setParameter(1, title)
.setParameter(2, category).getResultList().size();
return count > 0 ? true : false;
}
}
ArticleService:
#Service
public class ArticleService implements IArticleService {
#Autowired
private IArticleDAO articleDAO;
#Override
public Article getArticleById(int articleId) {
Article obj = articleDAO.getArticleById(articleId);
return obj;
}
#Override
public List<Article> getAllArticles(){
return articleDAO.getAllArticles();
}
#Override
public synchronized boolean createArticle(Article article){
if (articleDAO.articleExists(article.getTitle(), article.getCategory())) {
return false;
} else {
articleDAO.createArticle(article);
return true;
}
}
#Override
public void updateArticle(Article article) {
articleDAO.updateArticle(article);
}
#Override
public void deleteArticle(int articleId) {
articleDAO.deleteArticle(articleId);
}
}
and finally my REST controller:
#Controller
#RequestMapping("user")
#CrossOrigin(origins = {"http://localhost:4200"})
public class ArticleController {
#Autowired
private IArticleService articleService;
#GetMapping("article")
public ResponseEntity<Article> getArticleById(#RequestParam("id") String id) {
Article article = articleService.getArticleById(Integer.parseInt(id));
return new ResponseEntity<Article>(article, HttpStatus.OK);
}
#GetMapping("all-articles")
public ResponseEntity<List<Article>> getAllArticles() {
List<Article> list = articleService.getAllArticles();
return new ResponseEntity<List<Article>>(list, HttpStatus.OK);
}
#PostMapping("article")
public ResponseEntity<Void> createArticle(#RequestBody Article article, UriComponentsBuilder builder) {
boolean flag = articleService.createArticle(article);
if (flag == false) {
return new ResponseEntity<Void>(HttpStatus.CONFLICT);
}
HttpHeaders headers = new HttpHeaders();
headers.setLocation(builder.path("/article?id={id}").buildAndExpand(article.getArticleId()).toUri());
return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
}
#PutMapping("article")
public ResponseEntity<Article> updateArticle(#RequestBody Article article) {
articleService.updateArticle(article);
return new ResponseEntity<Article>(article, HttpStatus.OK);
}
#DeleteMapping("article")
public ResponseEntity<Void> deleteArticle(#RequestParam("id") String id) {
articleService.deleteArticle(Integer.parseInt(id));
return new ResponseEntity<Void>(HttpStatus.NO_CONTENT);
}
}
Did you create a Persistence Unit?
[Reference]=> https://docs.oracle.com/cd/E19798-01/821-1841/bnbrj/index.html
Once you already have the persistence-unit's tag defined you are able to create your entity manager like this:
private final String PERSISTENCE_UNIT_NAME = "PUName";
private EntityManagerFactory eMFactory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
EntityManager entityManager=eMFactory.createEntityManager();

Why canReveal() of GateKeeper was called before the EventHandler was called (GWT)?

I got a Header presenter which is the nested presenter. The Customer presenter is the child of Header presenter (ie the Customer presenter was put into a slot of Header presenter).
So I want to use MyGateKeeper to manage login page. The HeaderPresenter that will fire PassUserInfoEvent.
public class MyGateKeeper implements Gatekeeper{
private String loginedUserID="";
private final EventBus eventBus;
#Inject
public MyGateKeeper (final EventBus eventBus){
this.eventBus = eventBus;
this.eventBus.addHandler(PassUserInfoEvent.getType(), new PassUserInfoHandler(){
#Override
public void onPassUserInfo(PassUserInfoEvent event) {
// TODO Auto-generated method stub
String userID=event.getUserID();
loginedUserID=userID;
}
});
}
#Override
public boolean canReveal(){
System.out.println(loginedUserID+"Test");
if(!loginedUserID.equals("")){
System.out.println(loginedUserMeaningID+"cxcxc");
return true;
}
else{
return false;
}
}
}
In the CustomerPresenter:
#ProxyCodeSplit
#NameToken(NameTokens.cust)
#UseGatekeeper(MyGateKeeper.class)
public interface MyProxy extends ProxyPlace<CustomerPresenter> {
}
However after run, it does not show the Gui even I loggined. I tested & found that canReveal() in MyGateKeeper was called before PassUserInfoHandler() was called, so canReveal never return true;
How to fix this problem?
The usual pattern to accomplish this is to bind a CurrentUser class in Singleton:
bind(CurrentUser.class).in(Singleton.class);
and inject it into your GateKeeper. Inside your GateKeeper's canReveal method, you'll check that currentUser.isLoggedIn() :
private final CurrentUser currentUser;
#Inject
MyGateKeeper(CurrentUser currentUser) {
this.currentUser = currentUser;
}
#Override
public boolean canReveal() {
return currentUser.isLoggedIn();
}
You should initialize the CurrentUser.isLoggedIn field inside your Bootstrapper (see https://github.com/ArcBees/GWTP/wiki/Bootstrapping-or-Application-Initialization) by calling your server. Here's an example using GWTP's RestDispatch:
public class BootstrapperImpl implements Bootstrapper {
private final String unauthorizedPlace;
private final CurrentUser currentUser;
private final PlaceManager placeManager;
private final RestDispatch restDispatch;
private final UserResource userResource;
#Inject
BootstrapperImpl(
#UnauthorizedPlace String unauthorizedPlace,
CurrentUser currentUser,
PlaceManager placeManager,
RestDispatch restDispatch,
UserResource userResource) {
this.unauthorizedPlace = unauthorizedPlace;
this.currentUser = currentUser;
this.placeManager = placeManager;
this.restDispatch = restDispatch;
this.userResource = userResource;
}
#Override
public void onBootstrap() {
checkIfUserIsLoggedIn();
}
private void checkIfUserIsLoggedIn() {
restDispatch.execute(userResource.isCurrentUserLoggedIn(), new AbstractAsyncCallback<Boolean>() {
#Override
public void onSuccess(Boolean isCurrentUserLoggedIn) {
navigate(isCurrentUserLoggedIn);
}
});
}
private void navigate(Boolean isCurrentUserLoggedIn) {
currentUser.setLoggedIn(isCurrentUserLoggedIn);
if (isCurrentUserLoggedIn) {
placeManager.revealCurrentPlace();
} else {
placeManager.revealPlace(new PlaceRequest.Builder().nameToken(unauthorizedPlace).build());
}
}
}

Defining a resource assembler for a REST Spring HATEOAS controller

I'm trying to add HATEOAS links to a JSON resource served by a Spring REST controller.
I see I should use a resource assembler as described at https://github.com/spring-projects/spring-hateoas
The example displays a Person class and a PersonResource class.
I understand the PersonResource class is defined as:
public class PersonResource extends ResourceSupport {
}
What is then the Person class ? Is it a data domain class ?
In my case, I have defined an Admin class that is a REST domain class, and I specified it as having resource support:
public class Admin extends ResourceSupport {
private String firstname;
private String lastname;
private String email;
private String login;
private String password;
private String passwordSalt;
public Admin() {
}
public String getFirstname() {
return this.firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return this.lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getLogin() {
return this.login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPasswordSalt() {
return passwordSalt;
}
public void setPasswordSalt(String passwordSalt) {
this.passwordSalt = passwordSalt;
}
public EventAdmin toEventAdmin() {
EventAdmin eventAdmin = new EventAdmin();
BeanUtils.copyProperties(this, eventAdmin);
return eventAdmin;
}
public static Admin fromEventAdmin(EventAdmin eventAdmin) {
Admin admin = new Admin();
BeanUtils.copyProperties(eventAdmin, admin);
return admin;
}
}
My REST controller sees only this Admin class as it is a REST domain class. It does not know, and should not know, of anything data domain class.
So I wonder how to use the resource assembler support here.
I don't understand why I should have an additional data domain Admin class here.
kind Regards,
Following Mike's answer here is how my controller now looks like:
#RequestMapping(method = RequestMethod.POST, produces = "application/json; charset=utf-8")
#ResponseBody
public ResponseEntity<Admin> add(#RequestBody Admin admin, UriComponentsBuilder builder) {
AdminCreatedEvent adminCreatedEvent = adminService.add(new CreateAdminEvent(admin.toEventAdmin()));
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.add("Content-Type", "application/json; charset=utf-8");
responseHeaders.setLocation(builder.path("/admin/{id}").buildAndExpand(adminCreatedEvent.getAdminId()).toUri());
Admin createdAdmin = adminResourceAssembler.toResource(adminCreatedEvent.getEventAdmin());
ResponseEntity<Admin> responseEntity = new ResponseEntity<Admin>(createdAdmin, responseHeaders, HttpStatus.CREATED);
return responseEntity;
}
Before, instead of using the resource assembler I was doing a:
Admin createdAdmin = Admin.fromEventAdmin(adminCreatedEvent.getEventAdmin());
createdAdmin.add(linkTo(methodOn(AdminController.class).add(createdAdmin, builder)).withSelfRel());
But it was not giving me the resource id in the url.
Your ResourceAssembler implementation needs to know about both the data domain class and the REST domain class, because its job is to convert the former to the latter.
If you want to keep knowledge of your data classes out of your controller, you could make a resource conversion service which would retrieve the data from the repo and use a ResourceAssembler to turn it into resources that the controller can know about.
#Component
public class AdminResourceAssembler extends ResourceAssemblerSupport<Admin, AdminResource> {
public AdminResourceAssembler() {
super(AdminController.class, AdminResource.class);
}
public AdminResource toResource(Admin admin) {
AdminResource adminResource = createResourceWithId(admin.getId(), admin); // adds a "self" link
// TODO: copy properties from admin to adminResource
return adminResource;
}
}
#Service
public class AdminResourceService {
#Inject private AdminRepository adminRepository;
#Inject private AdminResourceAssembler adminResourceAssembler;
#Transactional
public AdminResource findOne(Long adminId) {
Admin admin = adminRepository.findOne(adminId);
AdminResource adminResource = adminResourceAssembler.toResource(admin);
return adminResource;
}
}
#Controller
#RequestMapping("/admins")
public class AdminController {
#Inject private AdminResourceService adminResourceService;
#RequestMapping(value="/{adminId}", method=RequestMethod.GET)
public HttpEntity<AdminResource> findOne(#PathVariable("adminId") Long adminId) {
AdminResource adminResource = adminResourceService.findOne(adminId);
return new ReponseEntity<>(adminResource, HttpStatus.OK);
}
}