简体   繁体   中英

Authorization of access to resources with spring security and Angularjs

I made permission to access resources in spring security as shown in this code: "The user authentication is then from the DB"

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{
     @Autowired
     protected void globalConfig(AuthenticationManagerBuilder auth, DataSource dataSource) throws Exception {
     //auth.inMemoryAuthentication().withUser("user").password("123").roles("USER");
         auth.jdbcAuthentication()
             .dataSource(dataSource)
             .usersByUsernameQuery("select username as principal, password as credentials, etat as actived from utilisateurs where username=?")
             .authoritiesByUsernameQuery("select u.username as principal, ur.nom_role as role from utilisateurs u inner join roles ur on(u.roles_id=ur.id_role) where u.username=?")
             .rolePrefix("ROLE_");
     }

 protected void configure(HttpSecurity http) throws Exception {
          http
         .csrf().disable()
           .sessionManagement().maximumSessions(100).maxSessionsPreventsLogin(false).expiredUrl("/Login");
          http
           .authorizeRequests()
           .antMatchers("/AppJS/**","/images/**","/pdf/**","/Template/**","/Views/**","/MainApp.js").permitAll()
           .antMatchers("/Users/**").access("hasRole('ADMIN')")
           .antMatchers("/Dashbord/**").access("hasRole('ADMIN')")
           .antMatchers("/Login*").anonymous()
           .anyRequest().authenticated()
           .and()
         .formLogin().loginPage("/Login").permitAll()
           .defaultSuccessUrl("/home")
           .failureUrl("/Login?error=true")
           .and().exceptionHandling().accessDeniedPage("/Access_Denied")
           .and()
         .logout()
            .invalidateHttpSession(true)
            .clearAuthentication(true)
            .logoutUrl("/logout")
            .permitAll()
           .logoutSuccessUrl("/Login");


     }

}

Subsequently, I specified the views for each URL:

@Configuration
public class MvcConfig  extends WebMvcConfigurerAdapter{
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
      registry.addViewController("/Login").setViewName("Login");
       registry.addViewController("/Dashbord").setViewName("home");
       registry.addViewController("/logout").setViewName("Login");
       registry.addViewController("/Users").setViewName("Views/ListUsers");
    }
}

I used the angularJS routeProvider to keep track of URLs:

var app = angular.module('Mainapp', ['ngRoute','file-model','ui.bootstrap','ngMessages']);
app.config(function($routeProvider) {
    $routeProvider
        .when('/Users', {
                controller:'UsersController', 
                templateUrl: 'Views/ListUsers'
        })     
      .when('/Dashbord', {
              controller: 'ResultController',
             templateUrl: 'Views/home.html'
        });  
});

My problem is how to make the link of the access authorization that I defined in spring security with the URLs of angularjs ($ routeProvider)

Thank you, and Have a good day,

You could try enable html5mode , to get this

AngularJS: http://localhost:8080/Users

app.config(function($routeProvider, $locationProvider) {
   $routeProvider
    .when('/Users', {
            controller:'UsersController', 
            templateUrl: 'Views/ListUsers'
    })     
  .when('/Dashbord', {
          controller: 'ResultController',
         templateUrl: 'Views/home.html'
    });  

   $locationProvider.html5Mode(true)
});

I am not sure this will meets your requirement but yes i have already did before with the use of ngPermission . Before that you need list of the roles to set in your route.

.state('view1', {
        templateUrl: 'view1/view1.html',
        controller: 'View1Ctrl',
        resolve: {
            authorization: ["ngPermissionService", function (ngPermissionService) {

                //you need to call webserivce at this level for get all user's permissions and return it.

                return ngPermissionService.role(["admin"])  

            }]
        }
    });

For more details click here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM