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

02 March 2019

Spring security multiple authentication provider


In your WebSecurityConfigurerAdapter you will need to add more than auth

@Override

protected void configure(AuthenticationManagerBuilder auth) throws Exception {

    auth.authenticationProvider(new MyFirstAuthenticationProvider(userRepository, bCryptPasswordEncoder()));

    auth.authenticationProvider(new MySecondAuthenticationProvider(userRepository, bCryptPasswordEncoder()));

}

Then Create MyFirstAuthenticationProvider and MySecondAuthenticationProvider like:

public class MyFirstAuthenticationProvider extends DaoAuthenticationProvider {

    public MyFirstAuthenticationProvider(UserRepository userRepository,
                                              BCryptPasswordEncoder bCryptPasswordEncoder) {

        super.setPasswordEncoder(bCryptPasswordEncoder);
        super.setUserDetailsService(......)
        );
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return MyFirstAuthenticationToken.class.isAssignableFrom(authentication);
    }
}


public class MyFirstAuthenticationToken extends UsernamePasswordAuthenticationToken {

    public MyFirstAuthenticationToken(UserEntity principal, Object credentials,
                                                   Collection<? extends GrantedAuthority> authorities) {
        super(principal, credentials, authorities);
    }
}
And the same for MySecondAuthenticationProvider.

You will need to use the authentication providers/token in the authenticaiton/authorization filters.


18 March 2017

Using spwrap inside spring transactions

spwrap is a little library that simplify calls to database stored procedures in java.

Read this introduction to talk an idea about spwrap before continue reading this post.

We have talked before about how to use spwrap in spring boot application.

Today we will talk about a new feature just release in version 0.0.18, which is spwrap now can participate in spring transactions.

spwrap itself doesn't allow spanning transaction across DAO method calls. but as part of 0.0.18, it will participate in spring Transactions if spwrap is used inside spring and there's an active transaction.

Suppose we have a spring project with Datasource transaction manager is enabled.

And we have  SupplierDAO which is a spwrap DAO defined like this:


public interface SupplierDAO {

    @StoredProc("insert_new_supplier")
    void insertSupplier(@Param(VARCHAR) String name);
}

And we have a domain object supplier and its spring-data-jpa repository

@Entity
public class Supplier {

    @Id    @GeneratedValue(strategy = AUTO)
    private Long id;

    @Column(unique = true)
    private String name;

    public Long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
// -- repository
public interface SupplierRepo extends JpaRepository<Supplier, Long> {
}

And here's the service class:

@Service
public class SupplierService {

    private SupplierDAO supplierDAO;
    private SupplierRepo supplierRepo;

    public SupplierService(SupplierDAO supplierDAO, SupplierRepo supplierRepo) {
        this.supplierDAO = supplierDAO;
        this.supplierRepo = supplierRepo;
    }

    @Transactional
    public void add2Suppliers(){
        final String supplierName = "Abdullah";

        supplierDAO.insertSupplier(supplierName);   // << will rolled-back

        Supplier s2 = new Supplier();
        s2.setName(supplierName);
        supplierRepo.save(s2);      // throws exception
    }

    public List<Supplier> listSuppliers(){
        return supplierRepo.findAll();
    }
}

Now because the supplierDAO.insertSupplier(supplierName) insert supplier with name "Abdullah", and supplierRepo.save(s2) insert supplier with the same name, then spring frameowkr will throw DataAccessException subclass and rollback the entire transaction.

Which meaning the stored procedure that is executed as a result of calling supplierDAO.insertSupplier(supplierName) will be rollbacked as well. Again, this is a new feature as part of spwrap 0.0.18. 

You can see the full example at github: https://github.com/mhewedy/spwrap-examples/tree/master/spring-boot-transactions-mysql Don't forget, if you like the spwrap library, don't forget to like the project page at github.

02 March 2017

Using spwrap with Spring boot

spwrap is a tiny framework to make stored procedures call from java code an easy and fun task.

I've written a couple of posts about it.

Today, I am gonna show you how to use it from spring boot project.

The main point I want to emphasis here is to register DAO interfaces as Spring Bean so that I would be reused across your application:

@Configuration
public class Config {

    @Autowired
    private DataSource dataSource;

    @Bean
    public DAO dao(){
        return new DAO.Builder(dataSource)
                .config(new spwrap.Config().useStatusFields(false))
                .build();
    }

    @Bean
    public CustomerDAO customerDAO(DAO dao){
        return dao.create(CustomerDAO.class);
    }
}
See the github page https://github.com/mhewedy/spwrap-examples/tree/master/spring-boot-mysql for the complete project.

Learn more: https://github.com/mhewedy/spwrap/wiki/Using-with-Spring-Boot-other-DI-frameworks
Thanks to stored-procedure-proxy at: https://github.com/marschall/stored-procedure-proxy/wiki/Object-Lifetime

30 September 2016

Gradle is awsome

Gradle the build tool for Java and Android (and other languages) is really powerful.

I am brand new to gradle, this is the first time I try it, and I find it really powerful.

I am working - for fun - on some spring boot + angular project , I decided to go with gradle because I like Groovy (The language that grails is written as a DSL; however gradle is written in Java as well as groovy).

However Eclipse support is not as much good as Maven, but I started the spring boot using gradle as the build tool and every thing is fine.

Now I need to build the spring project as well as the angular project (which is based on angular-seed that uses npm and bower).

I find a plugin for gradle for this task (gradle-node-plugin), this plugin allow you to do:

gradle npm-install

so, the npm install command will run and that what I need, but I need it to run with gradle build command.

First the npm-install task of gradle run by default  package.js file found in src/main/java, So I have to write my own task to make it uses spring-boot conventions (src/main/resources/static)

And thanks to the author of this plugin, he makes it easily to extend his plugin, so I wrote:

task my_npm_install(type: NpmTask) {
description = "Installs dependencies from package.json"
workingDir = file("${project.projectDir}/src/main/resources/static")
args = ['install']
}

Here I am defining a new task (enhanced task), that is of type NpmTask (defined in gradle-node-plugin) then set some properties (defined by the parent task (NpmTask) ), so it can do the job.

so, now I can run: gradle my_npm_task and gradle now will run npm install against the correct package.json file.

What is remaining is to have the this task run after I run gradle build (the build task).

Thanks to the amazing tasks dependency feature provided by gradle, I can refer to some task (provided by java plugin - I think) and make it depends on another task (the one I wrote).

Like this: build.dependsOn(my_npm_install)

Then when I run gradle build, here's the output:

.....
......

So that, the build task will run my_npm_install: (here's the output of gradle build command):

:check
:nodeSetup SKIPPED
:my_npm_install
:build
.......
......

gradle run the my_npm_install task before the build task.

Again, gradle is much more powerful and flexible than maven, and have a better syntax as well.