Last active
August 12, 2017 22:37
-
-
Save BrunoDSouza/2ca7b6f53be6817630cc7ed922252109 to your computer and use it in GitHub Desktop.
Configurações Spring Security
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Entity | |
@Table(name="roles") | |
public class Role{ | |
public Role(){}; | |
public Role(Long cod, String role){ | |
this.codigo = cod; | |
this.descricao = role; | |
}; | |
@Id | |
@GeneratedValue(strategy = GenerationType.IDENTITY) | |
@Column(name="idrole") | |
private Long codigo; | |
@NotBlank | |
@Column(name="descricao") | |
private String descricao; | |
@NotNull | |
@Column(name="cod_status") | |
private TipoStatus status = TipoStatus.ATIVADO; | |
/*Getters and Setters*/ | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@EnableGlobalMethodSecurity(prePostEnabled = true) | |
@EnableWebSecurity | |
@EnableJpaRepositories(basePackageClasses = UsersRepository.class) | |
@Configuration | |
public class SecurityConfig extends WebSecurityConfigurerAdapter { | |
@Autowired private UserService userDetailsService; | |
@Autowired | |
protected void configureGlobal(AuthenticationManagerBuilder auth) throws Exception{ | |
auth.userDetailsService(userDetailsService) | |
.passwordEncoder(passwordEnconder()); | |
} | |
@Override | |
protected void configure(HttpSecurity http) throws Exception{ | |
http.csrf().disable() | |
.authorizeRequests() | |
.antMatchers("/produto").hasAnyRole(Acls.FUNC) | |
.antMatchers("/fornecedor").hasAnyRole(Acls.FUNC) | |
.antMatchers("/tipos").hasAnyRole(Acls.FUNC) | |
.antMatchers("/movimentacao").hasAnyRole(Acls.FUNC) | |
.antMatchers("/setor").hasAnyRole(Acls.FUNC) | |
.antMatchers("/produto/**").hasRole(Acls.ADMIN) | |
.antMatchers("/fornecedor/**").hasRole(Acls.ADMIN) | |
.antMatchers("/tipos/**").hasRole(Acls.ADMIN) | |
.antMatchers("/setor/**").hasRole(Acls.ADMIN) | |
.anyRequest().authenticated() | |
.and() | |
.formLogin() | |
.loginPage("/").permitAll() | |
.failureUrl("/login/?error=true").permitAll() | |
.defaultSuccessUrl("/home").permitAll() | |
.loginPage("/").permitAll() | |
.and() | |
.logout() | |
.logoutRequestMatcher(new AntPathRequestMatcher("/logout")) | |
.logoutSuccessUrl("/login/?logout").permitAll() | |
.invalidateHttpSession(true).permitAll() | |
.clearAuthentication(true) | |
.deleteCookies("SPRING_SECURITY_REMEMBER_MECOOKIE","JSESSIONID"); | |
} | |
@Override | |
public AuthenticationManager authenticationManagerBean() throws Exception { | |
return super.authenticationManagerBean(); | |
} | |
@Override | |
public void configure(WebSecurity web) throws Exception{ | |
web.ignoring() | |
.antMatchers("/layout/**", | |
"/stylesheets/**", | |
"/javascripts/**", | |
"/images/**"); | |
} | |
@Bean | |
public BCryptPasswordEncoder passwordEnconder(){ | |
BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder(); | |
return bCryptPasswordEncoder; | |
} | |
@Bean | |
public PasswordEncoder getPasswordEncoder() { | |
return new PasswordEncoder() { | |
@Override | |
public String encode(CharSequence charSequence) { | |
return charSequence.toString(); | |
} | |
@Override | |
public boolean matches(CharSequence charSequence, String s) { | |
return true; | |
} | |
}; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class UserDetailsCustom extends Users implements UserDetails { | |
private static final long serialVersionUID = 1L; | |
public UserDetailsCustom(final Users users) { | |
super(users); | |
} | |
@Override | |
public Collection<? extends GrantedAuthority> getAuthorities() { | |
return super.getRoles().stream() | |
.map(role -> new SimpleGrantedAuthority("ROLE_" + role.getDescricao())) | |
.collect(Collectors.toList()); | |
} | |
@Override | |
public String getPassword() { | |
return super.getSenha(); | |
} | |
@Override | |
public String getUsername() { | |
return super.getUsername(); | |
} | |
@Override | |
public boolean isAccountNonExpired() { | |
return true; | |
} | |
@Override | |
public boolean isAccountNonLocked() { | |
return true; | |
} | |
@Override | |
public boolean isCredentialsNonExpired() { | |
return true; | |
} | |
@Override | |
public boolean isEnabled() { | |
return true; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Entity | |
@Table(name="users") | |
@UsersConstraint | |
public class Users{ | |
/*Metodos Construtores*/ | |
public Users() {} | |
public Users(Users users) { | |
this.codigo = users.getCodigo(); | |
this.username = users.getUsername(); | |
this.email = users.getEmail(); | |
this.senha = users.getSenha(); | |
this.dtNascimento = users.getDtNascimento(); | |
this.roles = users.getRoles(); | |
} | |
@Id | |
@Column(name="idusuario", nullable = false) | |
@GeneratedValue(strategy = GenerationType.IDENTITY) | |
private Long codigo; | |
@NotBlank | |
@Column(name="usuario") | |
@Size(message="O tamanho do nome do usuario deve possuir no máximo 255 caracteres!", max = 255) | |
private String username; | |
@NotNull | |
@DateTimeFormat(pattern = "dd/MM/yyyy") | |
@Column(name="dt_nascimento") | |
private Date dtNascimento; | |
@NotBlank | |
@Email(message="Email é inválido!") | |
@Column(name="email") | |
private String email; | |
@NotBlank | |
@Size(message="A senha deve possuir no minimo 6 caracteres!", min = 6) | |
@Column(name="senha") | |
private String senha; | |
@NotNull | |
@Column(name="cod_status") | |
private TipoStatus status = TipoStatus.ATIVADO; | |
@NotNull | |
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval=false) | |
@JoinTable(name="users_roles", joinColumns = @JoinColumn(name = "cod_user"), inverseJoinColumns = @JoinColumn(name="cod_role")) | |
private Set<Role> roles; | |
/*Getters and Setters*/ | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Service | |
@Configurable | |
public class UserService implements UserDetailsService{ | |
@Autowired private BCryptPasswordEncoder bCryptPasswordEncoder; | |
@Autowired private UsersRepository usersRepository; | |
public Users findUserByNameOrEmail(String value){ | |
return usersRepository.findByUsernameOrEmailIgnoreCase(value, value).get(); | |
} | |
public Users findUserByNameOrEmail(String username, String email){ | |
return usersRepository.findByUsernameOrEmailIgnoreCase(username, email).get(); | |
} | |
public Users findUserByUsername(String username){ | |
return usersRepository.findByUsernameIgnoreCase(username); | |
} | |
/*Override method*/ | |
public Users findUserByUsername(String username, Long codigo){ | |
return usersRepository.findByUsernameIgnoreCaseAndCodigoNot(username, codigo); | |
} | |
public Users findUserByEmail(String email){ | |
return usersRepository.findByEmailIgnoreCase(email); | |
} | |
/*Override method*/ | |
public Users findUserByEmail(String email, Long codigo){ | |
return usersRepository.findByEmailIgnoreCaseAndCodigoNot(email, codigo); | |
} | |
public Users findOne(Long codigo){ | |
return usersRepository.findOne(codigo); | |
} | |
public List<Users> findAll(){ | |
return usersRepository.findAll(); | |
} | |
public void save(Users user){ | |
user.setSenha(bCryptPasswordEncoder.encode(user.getSenha())); | |
usersRepository.save(user); | |
} | |
public void delete(Users user){ | |
usersRepository.delete(user); | |
} | |
@Override | |
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { | |
Optional<Users> users = usersRepository.findByUsernameOrEmailIgnoreCase(username,username); | |
users.orElseThrow(() -> new UsernameNotFoundException("Usuário não encontrado!")); | |
return users.map(UserDetailsCustom::new).get(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment