15
Spring Security Diego Armando Gómez Mosquera. [email protected] 2017

Spring security 2017

Embed Size (px)

Citation preview

Page 1: Spring security 2017

SpringSecurityDiegoArmandoGómez

[email protected]

2017

Page 2: Spring security 2017

Agenda• QueesSpringSecurity• ArquitecturadeSpringSecurity• Configuraciones:

– Modulosdespringsecurityenmaven– web.xml– securityContext.xml– applicationContext.xml– AuthenticationProvider.java– Login.xhtml– ManageBeanlogin

Page 3: Spring security 2017

QueesSpringSecurity?

• EsunmodulodelframeworkdeSpringqueproporcionaserviciosdeseguridadparaaplicacionesJavaEE.

• FacilitalacapadeseguridadencualquieraplicaciónJavaEEsobreHTTP

Page 4: Spring security 2017

TecnologíassoportadasporSpringSecurity

• HTTPBASICauthenticationheaders(anIEFTRFC-basedstandard).• HTTPDigestauthenticationheaders(anIEFTRFC-basedstandard).• HTTPX.509clientcertificateexchange(anIEFTRFC-basedstandard).• LDAP(unenfoquemuycomúnparanecesidadesdeautenticaciónmultiplataforma,

específicamenteenentornosextensos)Form-basedauthentication(necesarioparainterfacesdeusuariosimples).

• OpenIDauthentication.• ComputerAssociatesSiteminder.JA-SIGCentralAuthenticationService.• TransparentauthenticationcontextpropagationforRemoteMethodInvocation

(RMI)andHttpInvoker.Automatic"remember-me"authentication.• Anonymousauthentication.• Run-asauthentication.

Page 5: Spring security 2017

TecnologíassoportadasporSpringSecurity

• JavaAuthenticationandAuthorizationService(JAAS)• ContainerintegrationwithJBoss,Jetty,ResinandTomcat(tambienpodemosusar

autenticacióngestionadaporelcontenedor)• JavaOpenSourceSingleSignOn(JOSSO)*• OpenNMSNetworkManagementPlatform*• AppFuse*• AndroMDA*• MuleESB*• DirectWebRequest(DWR)*• Grails*• Tapestry*

Page 6: Spring security 2017

ConfiguraciónMaven• SedebenconfigurarlosmodulosdelSpringSecurityenelpom.xmlMaven<dependencies><!-- ...other dependency elements ...--><dependency>

<groupId>org.springframework.security</groupId><artifactId>spring-security-web</artifactId><version>4.2.3.RELEASE</version>

</dependency><dependency>

<groupId>org.springframework.security</groupId><artifactId>spring-security-config</artifactId><version>4.2.3.RELEASE</version>

</dependency></dependencies>

Page 7: Spring security 2017

ConfiguraciónMaven• Sedebeagregarlalibreríacommons-loggingenelpom.xmlMaven

<dependency><groupId>commons-logging</groupId><artifactId>commons-logging</artifactId><version>1.1.3</version>

</dependency>

Page 8: Spring security 2017

Configuraciónweb.xml<?xml version="1.0"encoding="UTF-8"?><web-appversion="3.0"

xmlns="http://java.sun.com/xml/ns/javaee"xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance

xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

<filter><filter-name>springSecurityFilterChain</filter-name><filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>

</filter><filter-mapping>

<filter-name>springSecurityFilterChain</filter-name><url-pattern>/*</url-pattern>

</filter-mapping></web-app>

Page 9: Spring security 2017

ConfiguraciónSecurityContext.xml<?xmlversion="1.0"encoding="UTF-8"?><!--AuthorZathuracode Generator--><beans:beans xmlns="http://www.springframework.org/schema/security"xmlns:beans="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/securityhttp://www.springframework.org/schema/security/spring-security-4.2.xsdhttp://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-4.3.xsd">

<httpauto-config="true"><intercept-url pattern="/"access="permitAll"/><intercept-url pattern="/login.xhtml"access="permitAll"/><intercept-url pattern="/XHTML/*"access="hasRole('ROLE_USER')orhasRole('ROLE_ADMIN')"/>

<form-loginlogin-page="/login.xhtml"authentication-failure-url="/login.xhtml?authfailed=true"default-target-url="/XHTML/initialMenu.xhtml"always-use-default-target="false" /><logoutinvalidate-session="true"logout-success-url="/login.xhtml?loggedout=true"logout-url="/j_spring_security_logout"delete-cookies="JSESSIONID,SPRING_SECURITY_REMEMBER_ME_COOKIE"/>

<csrf disabled="true"/></http>

<authentication-manageralias="authenticationManager"><authentication-providerref="zathuraCodeAuthenticationProvider"/></authentication-manager>

</beans:beans>

Page 10: Spring security 2017

ConfiguraciónapplicationContext.xml<?xml version="1.0"encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xmlns:tx="http://www.springframework.org/schema/tx"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd

http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd">

<bean id="dataSource"class="org.springframework.jdbc.datasource.DriverManagerDataSource"><property name="driverClassName"value="org.postgresql.Driver"/><property name="url"value="jdbc:postgresql://127.0.0.1:5433/banco"/><property name="username"value="postgres"/><property name="password"value="postgres"/>

</bean>

<beanid="sessionFactory"class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"><propertyname="configLocation"value="classpath:hibernate.cfg.xml"/><propertyname="dataSource"ref="dataSource"/>

</bean>

<beanid="transactionManager"class="org.springframework.orm.hibernate4.HibernateTransactionManager"><propertyname="sessionFactory"ref="sessionFactory"/>

</bean>

<tx:annotation-driven transaction-manager="transactionManager"/>

<context:component-scan base-package="co"/>

<importresource="classpath:securityContext.xml"/></beans>

Page 11: Spring security 2017

ConfiguraciónAuthenticationProvider.java@Scope("singleton")@Component("zathuraCodeAuthenticationProvider")public class ZathuraCodeAuthenticationProvider implements AuthenticationProvider {/***SecurityImplementation*/@Overridepublic Authenticationauthenticate(Authenticationauthentication)throws AuthenticationException {Stringname =authentication.getName();Stringpassword =authentication.getCredentials().toString();

if (name.equals("admin")&&password.equals("admin")){finalList<GrantedAuthority>grantedAuths =new ArrayList<GrantedAuthority>();grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER"));

finalUserDetails principal =new User(name,password,grantedAuths);finalAuthenticationauth =new UsernamePasswordAuthenticationToken(principal,password,grantedAuths);

return auth;}else{return null;

}}

@Overridepublic boolean supports(Class<?>authentication){return authentication.equals(UsernamePasswordAuthenticationToken.class);

}}

Page 12: Spring security 2017

login.xhtml<?xml version="1.0"encoding="UTF-8"?><!DOCTYPEhtml><html xmlns="http://www.w3.org/1999/xhtml"

xmlns:h="http://java.sun.com/jsf/html"xmlns:p="http://primefaces.org/ui"xmlns:f="http://java.sun.com/jsf/core"xmlns:ui="http://java.sun.com/jsf/facelets"><h:head>

<title>Login</title><metaname="content-type"content="text/html;charset=UTF-8"/>

</h:head><h:body><h:form>

<p:growl id="msgGrowl"autoUpdate="true"showDetail="false"/><h2>Pleasesignin</h2>

<p:inputText id="usernameField"name="j_username"value="#{loginView.userId}"placeholder="admin"/>

<p:password id="passwordField"name="j_password"value="#{loginView.password}"placeholder="admin"feedback="false"/>

<p:commandButton value="Sign in"action="#{loginView.login}"update="msgGrowl"/></h:form></h:body>

</html>

Page 13: Spring security 2017

ManageBeanlogin@ViewScoped@ManagedBean(name ="loginView")public class LoginView {private String userId;private String password;@ManagedProperty(value ="#{authenticationManager}")private AuthenticationManager authenticationManager =null;

public AuthenticationManager getAuthenticationManager(){return authenticationManager;

}

public void setAuthenticationManager(AuthenticationManager authenticationManager){this.authenticationManager =authenticationManager;

}public Stringlogin(){try{Authenticationrequest=newUsernamePasswordAuthenticationToken(this.getUserId(),this.getPassword());Authenticationresult=authenticationManager.authenticate(request);SecurityContext securityContext =SecurityContextHolder.getContext();securityContext.setAuthentication(result);

((HttpSession)FacesContext.getCurrentInstance().getExternalContext().getSession(true)).setAttribute("SPRING_SECURITY_CONTEXT",securityContext);}catch(AuthenticationException e){FacesUtils.addErrorMessage("authfailed loginorpassword");return "/login.xhtml";

}return "/XHTML/initialMenu.xhtml";

}}

Page 14: Spring security 2017

Informacióndecontacto

• SitioWeb:www.vortexbird.com• Blog:http://blog.vortexbird.com• Contactovíamail:[email protected]• Teléfonos:+57- (3164824629)

Page 15: Spring security 2017