Showing posts with label spring-security. Show all posts
Showing posts with label spring-security. Show all posts

Spring Security + Hibernate : Enabling database login via Annotations

Hibernate Entities:

Employee.java
===========
package com.mycompany.myapp.entity;

import javax.persistence.*;
import java.util.*;

@Entity
@Table(name = "employee")
public class Employee {

    private long id;
    private String username;
    private String password;

    @Column(name = "enabled", columnDefinition = "boolean default true",
     nullable = false)
    private Boolean enabled = true;

    @Id
    @GeneratedValue
    @Column(name = "id")
    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

//...

//other getters, setters

}

EmployeeRoles.java:
============
package com.mycompany.myapp.entity;

import javax.persistence.*;


@Entity
@Table(name = "employee_roles")
public class EmployeeRoles{

 private int id;
 private String employeeCode;
 private String role;

 @Id
 @GeneratedValue
 @Column(name = "id")
 public int getId()
 {

     return id;

 }

 
 public void setId(int id)
 {

     this.id = id;

 }

//other getters, setters
}

Initial Roles:

src/main/resources/import.sql:
====================================
insert into employee_roles(employee_code,role) 
values('SOME_EMPLOYEE_CODE','ROLE_USER');

Spring Security config:

WebSecurityConfig.java:
===================
package com.mycompany.myapp;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
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
.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configuration
.EnableWebSecurity;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation
.ResourceHandlerRegistry;
import javax.sql.*;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/webjars/**","/webjars/","/img/**",
                 "/styles/**","/js/**","/api/1.0/get**", "/about.html")
                 .permitAll().anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
            .logout()
                .permitAll();
                
    }


    @Autowired
    DataSource dataSource;
    
    @Autowired
    public void configAuthentication(AuthenticationManagerBuilder auth) 
throws Exception {
         
            auth.jdbcAuthentication().dataSource(dataSource)
       .usersByUsernameQuery(
          "select username,password, enabled 
                           from employee where username=?")
         .authoritiesByUsernameQuery(
            "select employee_code, role 
                        from employee_roles where employee_code=?");
    }
}

Creating/registering new user in Crowd with Crowd REST java client

Put the dependecy in your pom.xml

<dependency>
<groupId>com.atlassian.crowd.client</groupId>
<artifactId>atlassian-crowd-rest-client</artifactId>
<version>1.1</version>
</dependency>

In your java code:
  1. import com.atlassian.crowd.embedded.api.PasswordCredential;
  2. import com.atlassian.crowd.exception.ApplicationPermissionException;
  3. import com.atlassian.crowd.exception.GroupNotFoundException;
  4. import com.atlassian.crowd.exception.InvalidAuthenticationException;
  5. import com.atlassian.crowd.exception.OperationFailedException;
  6. import com.atlassian.crowd.model.user.*;
  7. import com.atlassian.crowd.exception.UserNotFoundException;
  8. import com.atlassian.crowd.service.client.CrowdClient;
  9. import com.atlassian.crowd.integration.rest.service.factory.RestCrowdClientFactory;
  10. import com.atlassian.crowd.service.client.ClientPropertiesImpl;
  11. import com.atlassian.crowd.service.client.ClientResourceLocator;

public static int registerNewUser(String userName, String emailAddress, String password) {
//your crowd server settings
   String url = "http://auth.staging.company.com/crowd/";//crowd base url
   String applicationName = "appincrowd";
   String applicationPass = "apppassword";
   String groupName = "usergroup";//a user group under the app
   

   CrowdClient client = new RestCrowdClientFactory().newInstance(url, applicationName, applicationPass);
//initialze crowd client

   UserTemplate ut = new UserTemplate(userName);

   ut.setActive(true);//make it active
   ut.setEmailAddress(emailAddress);
   ut.setName(userName);
   PasswordCredential p = new PasswordCredential(password, false);
   client.addUser(ut, p);
   client.addUserToGroup(userName, groupName);//now add user to that group
}


Setting Crowd configuration with properties :
Instead of hard-coded crowd configuration we should read them from a properties file:
Properties crowdProp=//properties from your bean
 
   ClientPropertiesImpl newCrowdClient=ClientPropertiesImpl.newInstanceFromProperties(crowdProp);
   CrowdClient client = new RestCrowdClientFactory().newInstance(newCrowdClient);