<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/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd"> <http auto-config="true"> <intercept-url pattern="/rest/**" access="ROLE_USER" /> <logout/> </http> <authentication-manager> <authentication-provider> <user-service > <user name="user" password="pass" authorities="ROLE_USER" /> </user-service> </authentication-provider> </authentication-manager> </beans:beans>
@RequestMapping("/rest/api") @RestController public class RestController { @RequestMapping public Object getInfo() { return //some response MyClass; } }
RestTemplate restTemplate = new RestTemplate(); String url = "http://localhost:8080/rest/api"; HttpHeaders headers = new HttpHeaders(); headers.add("Authorization", "Basic QWxhZGRpbupvcRVuIHNlc2FtZQ=="); //here is some login and pass like this login:pass HttpEntity<String> request = new HttpEntity<String>(headers); MyClass myclass = restTemplate.exchange(url, HttpMethod.GET, request, MyClass.class).getBody();
<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/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd"> <beans:bean id="restAuthenticationEntryPoint" class="com.example.rest.security.RestAuthenticationEntryPoint"/> <http pattern="/rest/**" entry-point-ref="restAuthenticationEntryPoint" use-expressions="true" auto-config="false" create-session="stateless" > <custom-filter ref="authenticationTokenProcessingFilter" position="FORM_LOGIN_FILTER" /> <intercept-url pattern="/rest/**" access="isAuthenticated()" /> <logout /> </http> <beans:bean class="com.example.rest.security.CustomTokenAuthenticationFilter" id="authenticationTokenProcessingFilter"> <beans:constructor-arg type="java.lang.String" value="/rest/**"/> <beans:constructor-arg type="org.springframework.security.authentication.AuthenticationManager" ref="authManager"> </beans:constructor-arg> </beans:bean> <http auto-config="true"> <intercept-url pattern="/token/**" access="ROLE_USER" /> </http> <authentication-manager alias="authManager" erase-credentials="false"> <authentication-provider> <user-service > <user name="user" password="pass" authorities="ROLE_USER" /> </user-service> </authentication-provider> </authentication-manager> </beans:beans>
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint { @Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException ) throws IOException, ServletException { response.sendError( HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized" ); } }
public class CustomTokenAuthenticationFilter extends AbstractAuthenticationProcessingFilter { private AuthenticationManager authenticationManager; @Autowired private CryptService cryptService; //service which can decrypt token public CustomTokenAuthenticationFilter(String defaultFilterProcessesUrl, AuthenticationManager authenticationManager) { super(defaultFilterProcessesUrl); this.authenticationManager = authenticationManager; super.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher(defaultFilterProcessesUrl)); setAuthenticationManager(new NoOpAuthenticationManager()); setAuthenticationSuccessHandler(new TokenSimpleUrlAuthenticationSuccessHandler()); } public final String HEADER_SECURITY_TOKEN = "My-Rest-Token"; @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException { String token = request.getHeader(HEADER_SECURITY_TOKEN); Authentication userAuthenticationToken = parseToken(token); if (userAuthenticationToken == null) { throw new AuthenticationServiceException("here we throw some exception or text"); } return userAuthenticationToken; } @Override protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException { super.successfulAuthentication(request, response, chain, authResult); chain.doFilter(request, response); } // This method makes some validation depend on your application logic private Authentication parseToken(String tokenString) { try { String encryptedToken = cryptService.decrypt(tokenString); Token token = new ObjectMapper().readValue(encryptedToken, Token.class); return authenticationManager.authenticate( new UsernamePasswordAuthenticationToken(token.getUsername(), token.getPassword())); } catch (Exception e) { return null; } return null; } }
<Connector port="8443" protocol="org.apache.coyote.http11.Http11Protocol" maxThreads="150" SSLEnabled="true" scheme="https" secure="true" keystoreFile="${catalina.home}/conf/cert/keystore_server" keystorePass="changeit" truststoreFile="${catalina.home}/conf/cert/truststore_server" truststorePass="changeit" clientAuth="true" sslProtocol="TLS" />
public class CertificateAuthenticationServiceImpl implements CertificateAuthenticationService { private static final String keyStorePass = "changeit"; private static final String trustedStorePass = "changeit"; private static final File keyStore = new File(new CertificateAuthenticationServiceImpl().getClass().getResource("/authCertificate/keystore_client").getPath()); private static final File trustedStore = new File(new CertificateAuthenticationServiceImpl().getClass().getResource("/authCertificate/truststore_client").getPath()); private static final String certificateType = "jks"; public String httpGet(URL url) { String resp = null; try { final HttpParams httpParams = new BasicHttpParams(); final KeyStore keystore = KeyStore.getInstance(certificateType); keystore.load(new FileInputStream(keyStore), keyStorePass.toCharArray()); final KeyStore truststore = KeyStore.getInstance(certificateType); truststore.load(new FileInputStream(trustedStore), trustedStorePass.toCharArray()); final SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme(url.toURI().getScheme(), new SSLSocketFactory(keystore, keyStorePass, truststore), url.getPort())); final DefaultHttpClient httpClient = new DefaultHttpClient(new ThreadSafeClientConnManager(httpParams, schemeRegistry), httpParams); try { HttpGet httpget = new HttpGet(url.toString()); CloseableHttpResponse response = httpClient.execute(httpget); try { HttpEntity entity = response.getEntity(); if (entity != null) { resp = EntityUtils.toString(entity); } EntityUtils.consume(entity); } finally { response.close(); } } finally { httpClient.close(); } } catch (Exception e) { throw new RuntimeException(e); } return resp; } }
Source: https://habr.com/ru/post/245415/
All Articles