java - Spring secuirty don't let me get access to my protected static files -
i'm trying protect static html pages, since i'm using angularjs , html partials pages can accessed users have role.
so tried creating folder inside web-inf folder called private , put html files there , put in spring security configuration file path of these files annotation hasanyauthority this
.antmatchers("/privatepartials/protectedpartial.html").hasanyauthority("rolea")
also tried hasrole annotation this
.antmatchers("/privatepartials/protectedpartial.html").access("hasrole('rolea')")
but 403 error, if user doesn't have "rolea" have since print in console roles user have when logins.
i tried create folder inside resources folder doesn't work since user can view protected page doesn't matter role user have. think because have method in security configuration class lets users access resources.
@override public void configure(websecurity web) throws exception { web.ignoring().antmatchers("/resources/**", "/index.jsp", "/login.jsp", "/template/**", "/", "/error/**"); }
so how can protect html partials pages spring security, i'm using spring mvc 4.2.5.release
, spring secuirty 4.1.0.release
here folder structure
springmvcproject --web-pages --web-inf --resources --angular --controllers usercontroller.js --services userservice.js --partials --userpartials deleteuser.html app.js permissionconstants.js routes.js --css --private --privatepartials protegida.html --views index.html --source packages --controllers --usercontrollers usercontroller.java --secuirty secuirtyconfig.java
and here entire security config class
public class segurityconfig extends websecurityconfigureradapter { public segurityconfig() { super(); } @autowired private userdetailsservice userdetailsservice; @autowired private restunauthorizedentrypoint restauthenticationentrypoint; @autowired private accessdeniedhandler restaccessdeniedhandler; @autowired private authenticationsuccesshandler restauthenticationsuccesshandler; @autowired private authenticationfailurehandler restauthenticationfailurehandler; @autowired public void configureglobal(authenticationmanagerbuilder auth) throws exception { auth.userdetailsservice(userdetailsservice); } @override public void configure(websecurity web) throws exception { web.ignoring().antmatchers("/resources/angular/**", "/resources/bower_components/**", "/resources/css/**", "/resources/dist/**", "/resources/less/**", "/index.jsp", "/login.jsp", "/template/**", "/", "/error/**"); } @override protected void configure(httpsecurity http) throws exception { http .headers().disable() .csrf().disable() .authorizerequests() .antmatchers("/failure").permitall() .antmatchers("/v2/api-docs").hasanyauthority("admin") .antmatchers("/users/**").hasanyauthority("admin") .antmatchers("/resources/private/privatepartials/protegida.html").hasauthority("administrador") .antmatchers("/views/partials/usuariotemplates/crearusuario.html").hasauthority("administrador") .anyrequest().authenticated() .and() .exceptionhandling() .authenticationentrypoint(restauthenticationentrypoint) .accessdeniedhandler(restaccessdeniedhandler) .and() .formlogin() .loginprocessingurl("/login") .successhandler(restauthenticationsuccesshandler) .failurehandler(restauthenticationfailurehandler) .usernameparameter("username") .passwordparameter("password") .permitall() .and() .logout() .logouturl("/logout") .logoutsuccesshandler(new httpstatusreturninglogoutsuccesshandler()) .deletecookies("jsessionid") .permitall() .and(); }
and here if springconfig class
@configuration @enablewebmvc @componentscan({"config", "controllers", "security"}) public class configmvc extends webmvcconfigureradapter { @override public void addresourcehandlers(resourcehandlerregistry registry) { registry.addresourcehandler("/resources/**").addresourcelocations("/web-inf/resources/"); } @bean public urlbasedviewresolver setupviewresolver() { urlbasedviewresolver resolver = new urlbasedviewresolver(); resolver.setprefix("/web-inf/views/"); resolver.setsuffix(".jsp"); resolver.setviewclass(jstlview.class); return resolver; }
i use $routechangestart
, http-auth-interceptor
implement login of app ehre javascritp file
angular.module('sistemaactividades') .run(function ($rootscope, $location, $http, authsharedservice, session, user_roles, $q, $timeout) { $rootscope.$on('$routechangestart', function (event, next) { if (next.originalpath === "http://localhost:8080/springmvctemplateann/login" && $rootscope.authenticated) { console.log('entre en el primer if del interceptor'); event.preventdefault(); console.log('registrese'); } else if (next.access && next.access.loginrequired && !$rootscope.authenticated) { console.log('entre en el segundo if del interceptor') event.preventdefault(); $rootscope.$broadcast("event:auth-loginrequired", {}); } else if (next.access && !authsharedservice.isauthorized(next.access.authorizedroles)) { console.log('entre en el tercer if del interceptor') event.preventdefault(); $rootscope.$broadcast("event:auth-forbidden", {}); } }); // call when the client confirmed $rootscope.$on('event:auth-loginconfirmed', function (event, data) { console.log('login confirmed start ' + data); alert(data.tosource()); console.log('la urlvale' + $rootscope.requestedurl); $rootscope.loadingaccount = false; var nextlocation = ($rootscope.requestedurl ? $rootscope.requestedurl : "/crearrol"); console.log('la url2vale' + $rootscope.requestedurl); var delay = ($location.path() === "/loading" ? 1500 : 0); // console.log('la variable nextlocation vale ' + !!nextlocation); $timeout(function () { session.create(data); $rootscope.account = session; $rootscope.authenticated = true; $location.path(nextlocation).replace(); }, delay); }); // call when 401 response returned server $rootscope.$on('event:auth-loginrequired', function (event, data) { console.log("2do 401 segundo interceptor"); if ($rootscope.loadingaccount && data.status !== 401) { $rootscope.requestedurl = $location.path() $location.path('/loading'); } else { session.invalidate(); $rootscope.authenticated = false; $rootscope.loadingaccount = false; $location.path('/login'); } }); // call when 403 response returned server $rootscope.$on('event:auth-forbidden', function (rejection) { console.log("3 er 403 tercer interceptor"); $rootscope.$evalasync(function () { $location.path('/crearpermiso').replace(); }); }); });
here routes javascript file
angular.module('sistemaactividades') .config(['$routeprovider', 'user_roles', function ($routeprovider, user_roles) { $routeprovider. when('/', { templateurl: '/springmvctemplateann/resources/angular/templates/dashboardtemplates/dashboardtemplate.html', controller: 'dashboardctrl', access: { loginrequired: true, authorizedroles: "*" } }). when('/login', { templateurl: '/springmvctemplateann/resources/angular/templates/logintemplate/login.html', controller: 'logincontroller', access: { loginrequired: false, authorizedroles: [user_roles.all] } }). when('/logout', { templateurl: '/springmvctemplateann/resources/angular/templates/logintemplate/login.html', controller: 'logoutcontroller' }). when('/protegida', { templateurl: '/springmvctemplateann/resources/private/privatepartials/protegida.html', controller: 'usuarioctrl' }). }); }]);
my auth service in angularjs
angular.module('sistemaactividades') .service('authsharedservice', function ($rootscope, $http, authservice, session) { return { login: function (username, password, rememberme) { console.log('presione el click'); var config = { params: { username: username, password: password, rememberme: rememberme }, ignoreauthmodule: 'ignoreauthmodule' }; $http.post('http://localhost:8080/springmvctemplateann/login', '', config) .success(function (data, status, headers, config) { authservice.loginconfirmed(data); }).error(function (data, status, headers, config) { $rootscope.authenticationerror = true; session.invalidate(); }); }, getaccount: function () { $rootscope.loadingaccount = true; $http.get('security/account') .then(function (response) { authservice.loginconfirmed(response.data); }); }, isauthorized: function (authorizedroles) { console.log('los roles valen ' + authorizedroles); if (!angular.isarray(authorizedroles)) { if (authorizedroles == '*') { return true; } authorizedroles = [authorizedroles]; } var isauthorized = false; angular.foreach(authorizedroles, function (authorizedrole) { var authorized = (!!session.login && session.userroles.indexof(authorizedrole) !== -1); if (authorized || authorizedrole == '*') { isauthorized = true; } }); return isauthorized; } logout: function () { console.log('entre en el log de logut'); $rootscope.authenticationerror = false; $rootscope.authenticated = false; $rootscope.account = null; $http.get('http://localhost:8080/springmvctemplateann/logout'); session.invalidate(); authservice.logincancelled(); } }; });
my login service in angularjs
angular.module('sistemaactividades') .service('session', function () { this.create = function (data) { this.id = data.id; this.login = data.login; this.firstname = data.firstname; this.lastname = data.familyname; this.email = data.email; this.userroles = []; angular.foreach(data.authorities, function (value, key) { this.push(value.name); }, this.userroles); }; this.invalidate = function () { this.id = null; this.login = null; this.firstname = null; this.lastname = null; this.email = null; this.userroles = null; }; return this; });
my login controller in angularjs
angular.module('sistemaactividades') .controller('logincontroller', ['$rootscope', '$scope', 'authsharedservice', function ($rootscope, $scope, authsharedservice) { $scope.rememberme = true; $scope.login = function () { console.log('pressione click'); $rootscope.authenticationerror = false; authsharedservice.login( $scope.username, $scope.password, $scope.rememberme ); }; }]);
my logout controller in angularjs
angular.module('sistemaactividades') .controller('logoutcontroller', ['$rootscope', '$scope', 'authsharedservice', function ($rootscope, $scope, authsharedservice) { authsharedservice.logout(); }]);
my login page
<div class="bg-extended"> <div class="align-vertical-center"> <div class="container"> <div class="row"> <div class="well col-sm-offset-3 col-sm-6"> <div class="well-heading well-primary"> <h1>sign in account</h1> </div> <form class="well-body"> <div class="alert alert-dismissible alert-info"> <button type="button" class="close" data-dismiss="alert">×</button> <strong>usuarios de prueba!</strong> <br/> <ul> <li><strong>usuarionormal / laclave</strong> usuario normal</li> <li><strong>usuarioadmin / clave123</strong> admin</li> </ul> </div> <div class="form-group label-floating" ng-class="{ 'has-error is-focused' : authenticationerror}"> <label class="control-label" for="login">login</label> <input id="login" type="text" class="form-control" ng-model="username" required="required"/> <span ng-show="authenticationerror" class="help-block"> please check credentials , try again. </span> </div> <div class="form-group label-floating"> <label class="control-label" for="password">password</label> <input id="password" type="password" class="form-control" ng-model="password" required="required"/> </div> <div class="checkbox"> <label> <input type="checkbox" ng-model="rememberme"/><span> remember me</span> </label> </div> <br/> <div class="col-sm-offset-3 col-sm-6"> <button class="btn btn-lg btn-primary btn-block" ng-click="login()"> login </button> </div> </form> </div> </div> </div> </div>
my login controller in java
@controller
public class logincontroller {
@requestmapping(value = "/login", method = requestmethod.get) public string login(modelmap map) { return "login"; } @requestmapping(value = "/logout", method = requestmethod.get) public string logout(modelmap map, httpservletrequest request, httpservletresponse response) { authentication auth = securitycontextholder.getcontext().getauthentication(); system.out.println("el usuario vale en logout" + auth.getname().tostring()); if (auth != null) { new securitycontextlogouthandler().logout(request, response, auth); } return "/login"; }
}
edit: managed made spring security protect partials in private folder inside resources after refresh page or reload page lost session , can access private pages no matter role have, when refresh the page redirected login page , if login user have normal role user can enter admin protected pages
Comments
Post a Comment