<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Villy Siu on Medium]]></title>
        <description><![CDATA[Stories by Villy Siu on Medium]]></description>
        <link>https://medium.com/@villysiu?source=rss-8ddd87f6d448------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*6ApNHHPsFQqWkfjyepyvjw.jpeg</url>
            <title>Stories by Villy Siu on Medium</title>
            <link>https://medium.com/@villysiu?source=rss-8ddd87f6d448------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 00:40:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@villysiu/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Authentication with Spring Security, OAuth2 with GitHub and JWT]]></title>
            <link>https://medium.com/@villysiu/authentication-with-spring-security-oauth2-with-github-and-jwt-554cdd97922d?source=rss-8ddd87f6d448------2</link>
            <guid isPermaLink="false">https://medium.com/p/554cdd97922d</guid>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[spring-security]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[oauth2]]></category>
            <dc:creator><![CDATA[Villy Siu]]></dc:creator>
            <pubDate>Thu, 10 Apr 2025 21:33:06 GMT</pubDate>
            <atom:updated>2025-04-12T02:24:23.231Z</atom:updated>
            <content:encoded><![CDATA[<iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FLYDzl2VVj48%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DLYDzl2VVj48&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FLYDzl2VVj48%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/6cc92a0de48b21aacff4ce8ae0a71a3e/href">https://medium.com/media/6cc92a0de48b21aacff4ce8ae0a71a3e/href</a></iframe><h4>GitHub Link</h4><p><a href="https://github.com/villysiu/SpringSecurityOauth2Demo.git">https://github.com/villysiu/SpringSecurityOauth2Demo.git</a></p><p>In this tutorial, we are going to add GitHub authentication to my previous project, <a href="https://github.com/villysiu/SpringSecurityRestAPIJWTDemo.git">SpringSecurityRestAPIJWTDemo</a> .</p><p>We will be adding <em>Spring Security OAuth2 dependency,</em> since Spring Security OAuth 2.0 dependency is very well established and we can add the lease code and minimal customization to get JWT and authentication working.</p><h3><strong>How OAuth 2.0 works</strong></h3><p>To understand how to use external resources, such as GitHub, Google, Facebook, to authenticate, we have to understand how OAuth 2.0 works first.</p><p>In OAuth 2.0, there are 4 key roles:</p><ol><li><strong>Resource Owner</strong> — usually the user. (ie. github user)</li><li><strong>Client</strong> — the app wanting access to user data (ie our demo app).</li><li><strong>Authorization Server</strong> — issues tokens after user grants permission. (ie. github.com)</li><li><strong>Resource Server</strong> — the API or service holding the actual data.(ie. github.com)</li></ol><p>Example:</p><ul><li>You grant permission through GitHub (the authorization server).</li><li>The demo app gets an access token.</li><li>The demo app sends a request with the token to the GutHub API (the resource server).</li><li>GutHub API checks the token → then returns the GitHub user.</li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FxKQlUSX6nqI%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DxKQlUSX6nqI&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FxKQlUSX6nqI%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/f205adb15d874d23592799102bea7e05/href">https://medium.com/media/f205adb15d874d23592799102bea7e05/href</a></iframe><p><em>Note</em> <em>that in the video above, we are only getting the GitHub user information and we have not integrated any of these into our demo app yet.</em></p><h3>How OAuth 2.0 works in our demo</h3><ul><li>Visit <a href="http://localhost:8080/oauth2/authorization/github">http://localhost:8080/oauth2/authorization/github</a> in the browser, or through a button if we have a frontend.</li><li>You grant permission through GitHub by entering valid credential.</li><li>Once authenticated, we will use the configuration in oauth2Login. <br>What happen behind the scene and done automatically by oauth2Login ,</li><li>receive a code from GitHub<br>- exchange an access token with the code from GitHub<br>- request user information with the access token <br>- the user information will be saved in the SecurityContextHolder with GitHub user info.</li><li>We will override the process by adding our own customized <strong>customAuthorizedClientService</strong>. The customized service <br>- save the user into the database if not already existed.<br>- generate a Jwt token</li></ul><h3>About The Demo</h3><p>This application allows user to</p><ul><li>sign up with email and password</li><li>login with valid credential</li><li><strong>login through GitHub authentication by OAuth 2.0</strong></li></ul><p>Since both Postman and Insomnia do not support redirection within the Oauth2Login, we will be using the browser to demonstrate the authentication process with GitHub. <br><br>The configuration of my system</p><ul><li>Intellij Idea</li><li>Springboot 3.4.2</li><li>Java 17</li><li>JDK 23</li></ul><p>Maven dependencies for the project:</p><ul><li>Spring Boot DevTools</li><li>Spring Web</li><li>Spring Client</li><li>Lombok</li><li>JDBC API</li><li>Spring Data JPA</li><li>MySQL</li><li>Json Web token</li></ul><h4>pom.xml</h4><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.security&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-security-oauth2-jose&lt;/artifactId&gt;<br>    &lt;version&gt;6.4.4&lt;/version&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-starter-oauth2-client&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><h4>SecureConfig</h4><pre>.oauth2Login(config -&gt; config<br>    .authorizedClientService(this.customAuthorizedClientService)<br>    .defaultSuccessUrl(&quot;/secure/github_login_success&quot;, true)<br>)<br><br>Setting up GitHub Authentication</pre><h4>CustomAuthorizedClientService</h4><p>we customized `OAuth2AuthorizedClientService` so we can save the authenticated OAuth2User into our `Account` database if it is not already existed.<br>Then we generated a JWT token with the email from the Oauth2User object.</p><h4>/secure/github_login_success</h4><p>When we are redirected to `/secure/github_login_success`, we will hit the JwtAuthenticationFilter first, which will validate the JWT token in the cookie, and persisted the UserDetails object in the SecurityContextHolder,<br>which can be accessed from Authentication.</p><h4>Please visit GitHub Link</h4><p><a href="https://github.com/villysiu/SpringSecurityOauth2Demo.g">https://github.com/villysiu/SpringSecurityOauth2Demo.g</a>it and follow the <a href="https://github.com/villysiu/SpringSecurityOauth2Demo#cloning-the-project">instruction</a> in Readme.md to start testing out the application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=554cdd97922d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Authentication with Spring Security and JSON Web Token (JWT)]]></title>
            <link>https://medium.com/@villysiu/login-and-signup-with-spring-security-and-json-web-token-jwt-db0ec14e192b?source=rss-8ddd87f6d448------2</link>
            <guid isPermaLink="false">https://medium.com/p/db0ec14e192b</guid>
            <dc:creator><![CDATA[Villy Siu]]></dc:creator>
            <pubDate>Sun, 09 Mar 2025 05:33:31 GMT</pubDate>
            <atom:updated>2025-03-25T18:09:13.198Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4kmMGfCuHJPtB4t0s5l30Q.png" /></figure><p>In this tutorial, we are building an authentication REST API Spring boot project with Spring Security and Jwt token.</p><p>This is based on my previous post <a href="https://medium.com/@villysiu/java-springboot-signup-login-rest-api-d01b21759ba9">Java Springboot signup/login Rest API</a>. Instead of persisting the authenticated user into a HttpSession, we create a JSON Web Token with the authenticated user’s email and persist it in a cookie in the response header. So everytime a request being sent, the cookie will be sent along, and jwt token will be extracted and validated, to see if user has authority to visit the link.</p><p>The configuration of my system</p><ul><li>Springboot 3.4.2</li><li>Java 17</li><li>JDK 23</li></ul><h3>Create Spring boot application</h3><p>Spring Boot provides a web tool called <a href="https://start.spring.io/"><strong>Spring Initializer</strong></a> to bootstrap an application quickly. Just go to <a href="https://start.spring.io/"><strong>https://start.spring.io/</strong></a> and generate a new spring boot project with Maven or use Intellij Idea.</p><p>Maven dependencies for the project:</p><ul><li>Spring Boot DevTools</li><li>Spring Web</li><li>Spring Security</li><li>Lombak</li><li>JDBC API</li><li>Spring Data JPA</li><li>MySQL</li></ul><h3>Create MySQL database</h3><p>Create a new database, springbootRestApiJWT, in MySQL server.</p><h3>Setup connection to database</h3><p>in /src/main/resources/application.properties, added the following text</p><pre>spring.application.name=SpringSecurityRestAPI<br><br>spring.datasource.url = jdbc:mysql://localhost:3306/springbootRestApiJWT?useSSL=false&amp;serverTimezone=UTC<br>spring.datasource.username = &lt;-- insert your MySQL username --&gt;<br>spring.datasource.password = &lt;-- insert your MySQL password --&gt;<br><br># hibernate properties<br>spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQLDialect<br><br># Hibernate ddl auto (create, create-drop, validate, update)<br>spring.jpa.hibernate.ddl-auto = update<br><br>logging.level.org.springframework.security=DEBUG<br><br><br>#jwt.token.secret<br><br>jwt.token.secret=${SECRET_KEY}<br>jwt.token.expires=30</pre><p>The last 3 lines are for generating jwt token and decode . The token expiration time is saved as 30 minutes. These values will be injected to @Value for use.</p><h3>Create a secret</h3><p>Generate a secret key from <a href="https://jwtsecret.com/generate">https://jwtsecret.com/generate</a>.</p><p>On the bar on top, SpringSecurityRestApiApplication -&gt; Edit Configuration</p><p>Look for Edit Option, enable Environment Variable by checking it.</p><p>In the Environment Variable input box, enter</p><pre>SECRET_KEY=&lt;-- the 128 bit secret key --&gt;</pre><p>Click Apply, then Ok.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zxdHRp-OaBTiq3XsDFFpGw.png" /></figure><h3><strong>pom.xml</strong></h3><p>Add the following dependencies in pom.xml in use jwt token, validation and logging. Press the <strong>M</strong> button to open the Maven panel and sync/refresh the maven project. Check out <a href="https://mvnrepository.com/open-source/json-web-tokens-libraries">mavenrepository.com</a> for latest version.</p><pre>&lt;!-- Validation --&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;jakarta.validation&lt;/groupId&gt;<br>    &lt;artifactId&gt;jakarta.validation-api&lt;/artifactId&gt;<br>    &lt;version&gt;3.0.2&lt;/version&gt;<br>&lt;/dependency&gt;<br><br><br>&lt;!-- json web token --&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;io.jsonwebtoken&lt;/groupId&gt;<br>    &lt;artifactId&gt;jjwt-impl&lt;/artifactId&gt;<br>    &lt;version&gt;0.12.6&lt;/version&gt;<br>    &lt;scope&gt;runtime&lt;/scope&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;io.jsonwebtoken&lt;/groupId&gt;<br>    &lt;artifactId&gt;jjwt-api&lt;/artifactId&gt;<br>    &lt;version&gt;0.12.6&lt;/version&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;io.jsonwebtoken&lt;/groupId&gt;<br>    &lt;artifactId&gt;jjwt-jackson&lt;/artifactId&gt;<br>    &lt;version&gt;0.12.6&lt;/version&gt;<br>    &lt;scope&gt;runtime&lt;/scope&gt;<br>&lt;/dependency&gt;<br><br>&lt;!-- Logging --&gt;<br>&lt;!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api --&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;org.slf4j&lt;/groupId&gt;<br>    &lt;artifactId&gt;slf4j-api&lt;/artifactId&gt;<br>    &lt;version&gt;2.0.16&lt;/version&gt;<br>&lt;/dependency&gt;</pre><h3>Model/Entity</h3><p>Create the model package in /src/main/java/com.villysiu.springsecurityrestapi . In the newly created model package, we will create the two entities, Account.java and Role.java, and an Enum class containing the Roles, ROLE_USER and ROLE_ADMIN.</p><pre>@Entity<br>@Table<br>@Data<br>@Builder<br>@NoArgsConstructor<br>@AllArgsConstructor<br><br>public class Account {<br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private long id;<br><br>    @NotBlank(message = &quot;Name is required&quot;)<br>    private String nickname;<br><br>    @NotBlank(message = &quot;email is required&quot;)<br>    @Email<br>    @Column(unique = true)<br>    private String email;<br><br>    @NotBlank(message = &quot;Password is required&quot;)<br>    private String password;<br><br>    @ManyToMany(fetch = FetchType.EAGER )<br>    @JoinTable(name = &quot;account_roles&quot;,<br>            joinColumns = @JoinColumn(name = &quot;account_id&quot;),<br>            inverseJoinColumns = @JoinColumn(name = &quot;role_id&quot;))<br>    private Set&lt;Role&gt; roles = new HashSet&lt;&gt;();<br><br>    public Account(String nickname, String email, String password) {<br>        this.nickname = nickname;<br>        this.email = email;<br>        this.password = password;<br>    }<br>}</pre><pre>@Entity<br>@Data<br>@NoArgsConstructor<br>public class Role {<br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private Long id;<br><br>    @Enumerated(EnumType.STRING)<br>    private ERole erole = ERole.ROLE_USER;<br><br>    public Role(ERole erole) {<br>        this.erole = erole;<br>    }<br>}</pre><pre>public enum ERole {<br>    ROLE_USER,<br>    ROLE_ADMIN<br>}</pre><h3>Repository and JPA</h3><p>Next we will create the repository package in /src/main/java/com.villysiu.springsecurityrestapi and create AccountRepository.java and RoleRepository.java that extends JpaRepository to interact with the database using the Java Persistence API (JPA). JPA provides built-in methods for basic CRUD operations, ie.save(), findById(), findAll(), and delete() and <strong>Pagination and Sorting, ie.</strong>findAll(Pageable pageable) and findAll(Sort sort).</p><pre>@Repository<br>public interface AccountRepository extends JpaRepository&lt;Account, Long&gt; {<br>    Optional&lt;Account&gt; findByEmail(String email);<br>    Boolean existsByEmail(String email);<br>}</pre><pre>@Repository<br>public interface RoleRepository extends JpaRepository&lt;Role, Long&gt; {<br>    Optional&lt;Role&gt; findByErole(ERole erole);<br>}</pre><h3>Service</h3><p>we will create the service package in /src/main/java/com.villysiu.springsecurityrestapi and create a CustomUserDetailsService.java which implements the <a href="https://docs.spring.io/spring-security/reference/servlet/authentication/passwords/user-details-service.html">UserDetailsService</a> interface.</p><pre>@Service<br>public class CustomUserDetailsService implements UserDetailsService {<br><br>    private  AccountRepository accountRepository;<br>    public CustomUserDetailsService(AccountRepository accountRepository) {<br>        this.accountRepository = accountRepository;<br>    }<br><br>    @Override<br>    public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {<br>        Account account = accountRepository.findByEmail(email)<br>                .orElseThrow(() -&gt;<br>                        new UsernameNotFoundException(email + &quot; not found.&quot; ));<br><br>        Set&lt;GrantedAuthority&gt; authorities = account<br>                .getRoles()<br>                .stream()<br>                .map((role) -&gt; new SimpleGrantedAuthority(role.getErole().name()))<br>                .collect(Collectors.toSet());<br><br>        return new org.springframework.security.core.userdetails.User(<br>                account.getEmail(),<br>                account.getPassword(),<br>                authorities<br>        );<br>    }<br>}</pre><h3>JwtService</h3><p>In service package, we create the JwtService.java, which contains the business login of jwt.</p><p>void generateToken(String email, HttpServletResponse response)generates a jwt token with Jwts.builder() and persists the token in a cookie, “JWT”, in http response header. When user makes a request to the API, the cookie will be passed along in header and be verfied.</p><p>void validateToken(String token) throws JwtExceptionvalidates the token. If token is empty, expired, or not in valid format, JwtException will be thrown.</p><p>String getJwtTokenFromCookie(HttpServletRequest request)extracts the token from “JWT” cookie.</p><p>void removeTokenFromCookie(HttpServletResponse response)sets the “JWT” cookie to null.</p><p>String extractEmail()extracts the user’s email</p><pre>@Service<br>public class JwtService {<br><br>    // set in .env<br>    @Value(&quot;${jwt.token.secret}&quot;)<br>    private String secret;<br><br>    @Value(&quot;${jwt.token.expires}&quot;)<br>    private Long jwtExpiresMinutes;<br><br>    private Claims claims;<br><br>    public void generateToken(String email, HttpServletResponse response){<br>        String jwt = Jwts.builder()<br>                .subject(email) //username here is indeed the email<br>                .issuedAt(new Date(System.currentTimeMillis()))<br>                .expiration(new Date(System.currentTimeMillis() + jwtExpiresMinutes * 60 * 1000))<br>                .signWith(getSignInKey())<br>                .compact();<br><br>        Cookie cookie = new Cookie(&quot;JWT&quot;, jwt);<br>        cookie.setHttpOnly(true);<br>        cookie.setSecure(true);<br>        cookie.setPath(&quot;/&quot;);<br>        cookie.setMaxAge(24 * 60 * 60);<br>        response.addCookie(cookie);<br>    }<br><br>    public String getJwtFromCookie(HttpServletRequest request){<br>        Cookie cookie = WebUtils.getCookie(request, &quot;JWT&quot;);<br>        if(cookie != null){<br>            return cookie.getValue();<br>        }<br>        return null;<br><br>    }<br>    public void validateToken(String token) throws JwtException {<br><br>        try {<br>            claims = Jwts.parser()<br>                    .verifyWith(getSignInKey())<br>                    .build()<br>                    .parseSignedClaims(token)<br>                    .getPayload();<br><br><br>        } catch(JwtException e){<br>// catch null, wrong token, expired token<br>            throw new JwtException(e.getMessage());<br>        }<br>    }<br>    public void removeTokenFromCookie(HttpServletResponse response){<br>        Cookie cookie = new Cookie(&quot;JWT&quot;, null);<br>        cookie.setPath(&quot;/&quot;);<br><br>        response.addCookie(cookie);<br>    }<br><br>    private SecretKey getSignInKey() {<br>//        SignatureAlgorithm.HS256, this.secret<br>        byte[] keyBytes = Decoders.BASE64.decode(this.secret);<br>        return Keys.hmacShaKeyFor(keyBytes);<br>    }<br><br>    public String extractEmail() {<br>        return claims.getSubject();<br>    }<br><br>}</pre><h3>AuthenticationService</h3><p>In service package, we create the AuthenticationService.java, which contains the business logic of authentication through Spring Security, including login, signup and logout.</p><pre>@Service<br>public class AuthenticationService {<br><br>    private final AuthenticationManager authenticationManager;<br>    private final PasswordEncoder passwordEncoder;<br>    private final AccountRepository accountRepository;<br>    private final JwtService jwtService;<br>    private final RoleRepository roleRepository;<br><br>    public AuthenticationService(AuthenticationManager authenticationManager, PasswordEncoder passwordEncoder, AccountRepository accountRepository,  JwtService jwtService, RoleRepository roleRepository) {<br>        this.authenticationManager = authenticationManager;<br>        this.passwordEncoder = passwordEncoder;<br>        this.accountRepository = accountRepository;<br>        this.jwtService = jwtService;<br>        this.roleRepository = roleRepository;<br>    }<br>    public String login(LoginRequest loginRequest, HttpServletResponse response) {<br><br>        Authentication authenticationRequest = UsernamePasswordAuthenticationToken.unauthenticated(loginRequest.getEmail(), loginRequest.getPassword());<br>        Authentication authenticationResponse = this.authenticationManager.authenticate(authenticationRequest);<br><br>        SecurityContextHolder.getContext().setAuthentication(authenticationResponse);<br>        jwtService.generateToken(loginRequest.getEmail(), response);<br>        UserDetails userDetails = (UserDetails) authenticationResponse.getPrincipal();<br>        return userDetails.getUsername();<br>    }<br>    public void registerAccount(SignupRequest signupRequest){<br>        if(accountRepository.existsByEmail(signupRequest.getEmail())){<br>            throw new EntityExistsException(&quot;Email already used&quot;);<br>        }<br>        // create user object<br>        Account account = new Account(signupRequest.getName(), signupRequest.getEmail(), passwordEncoder.encode(signupRequest.getPassword()));<br>        Role role = roleRepository.findByErole(ERole.ROLE_USER).orElse(null);<br>        account.setRoles(Collections.singleton(role));<br>        accountRepository.save(account);<br><br>    }<br>    public void logoutUser(HttpServletResponse response){<br>        jwtService.removeTokenFromCookie(response);<br>    }<br>}</pre><h3>JwtAuthenticationFilter</h3><p>In the config package, we will create the JwtAuthenticationFilter.java, which extends OncePerRequestFilter and override the doFilterInternal() method. OncePerRequestFilter, as its name said, is executed only once for a given request. When <strong>a </strong>HttpServletRequest comes in from an api client, we check the header for the cookie to extract Bearer token. If there is a valid Bearer token, we stored the user into the SecurityContextHolder, (which can be accessed by @AuthenticationPrincipal UserDetails userDetails) then we will continue in the chain of filter. To learn more about filter and chain of filter, check <a href="https://docs.spring.io/spring-security/reference/servlet/architecture.html#servlet-securityfilterchain">Spring docs</a> out.</p><pre>@Component<br>public class JwtAuthenticationFilter extends OncePerRequestFilter {<br>    private final JwtService jwtService;<br>    private final CustomUserDetailsService customUserDetailsService;<br>    public JwtAuthenticationFilter(JwtService jwtService, CustomUserDetailsService customUserDetailsService) {<br>        this.jwtService = jwtService;<br>        this.customUserDetailsService = customUserDetailsService;<br>    }<br>    private static final Logger logger = LoggerFactory.getLogger(JwtAuthenticationFilter.class);<br><br>    @Override<br>    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {<br><br>        try {<br>            String jwt = jwtService.getJwtFromCookie(request);<br>            jwtService.validateToken(jwt);<br>            String userEmail = jwtService.extractEmail();<br><br>            UserDetails userDetails = customUserDetailsService.loadUserByUsername(userEmail);<br><br>            UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());<br>            authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));<br><br>            SecurityContext context = SecurityContextHolder.createEmptyContext();<br>            context.setAuthentication(authToken);<br>            SecurityContextHolder.setContext(context);<br><br><br>        } catch (Exception e) {<br>            logger.error(&quot;Invalid JWT token: {}&quot;, e.getMessage());<br>        }<br>        filterChain.doFilter(request, response);<br>    }<br>}</pre><h3>SecurityConfig</h3><p>In SecurityConfig.java, we added the following line to run JwtAuthenticationFilter before the rest of the application.</p><pre>.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);</pre><p>we changed Session to stateless because we no longer rely on server side for session management, as JWT wraps the informaton and stored in the cookie, which is sent in header along with any request.</p><pre>.sessionManagement(manager -&gt; manager<br>    .sessionCreationPolicy(SessionCreationPolicy.STATELESS))</pre><p>Completed SecurityConfig.java Code</p><pre>@Configuration<br>@EnableWebSecurity<br>public class SecurityConfig {<br><br>    @Autowired<br>    private JwtAuthenticationFilter jwtAuthenticationFilter;<br><br>    @Bean<br>    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {<br>        http<br>                .csrf(AbstractHttpConfigurer::disable)<br>                .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)<br>                .exceptionHandling(exceptionHandling -&gt;<br>                                exceptionHandling<br>                                .authenticationEntryPoint(new RestAuthenticationEntryPoint())<br>                )<br>                .authorizeHttpRequests((auth) -&gt;<br>                        auth.requestMatchers(HttpMethod.GET, &quot;public_resource&quot;).permitAll()<br>                                .requestMatchers(&quot;/auth/**&quot;).permitAll()<br>                                .anyRequest().authenticated()<br>                )<br>                .sessionManagement(manager -&gt; manager<br>                        .sessionCreationPolicy(SessionCreationPolicy.STATELESS));<br><br>        return http.build();<br>    }<br><br>    @Bean<br>    public AuthenticationManager authenticationManager(UserDetailsService userDetailsService, PasswordEncoder passwordEncoder) {<br>        DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();<br>        authenticationProvider.setUserDetailsService(userDetailsService);<br>        authenticationProvider.setPasswordEncoder(passwordEncoder);<br><br>        return new ProviderManager(authenticationProvider);<br>    }<br><br>    @Bean<br>    public static PasswordEncoder passwordEncoder(){<br>        return new BCryptPasswordEncoder();<br>    }<br>}</pre><h3>Login Controller</h3><pre>@PostMapping(&quot;/signin&quot;)<br>    public ResponseEntity&lt;?&gt; login(@RequestBody LoginRequest loginRequest, HttpServletResponse response){<br>        try {<br>            String email = authenticationService.login(loginRequest, response);<br>            return new ResponseEntity&lt;&gt;(email+&quot; signed in&quot;, HttpStatus.OK);<br>        } catch (Exception e) {<br>            logger.error(e.getMessage());<br>            return new ResponseEntity&lt;&gt;(e.getMessage(), HttpStatus.UNAUTHORIZED);<br>        }<br>}</pre><h3>Signup Controller</h3><pre>@PostMapping(&quot;/signup&quot;)<br>    public ResponseEntity&lt;?&gt; registerUser(@RequestBody SignupRequest signupRequest, HttpServletRequest request){<br>        try {<br>            authenticationService.registerAccount(signupRequest);<br>            return new ResponseEntity&lt;&gt;(&quot;Account registered.&quot;, HttpStatus.CREATED);<br>        } catch (Exception e) {<br>            logger.error(e.getMessage());<br>            return new ResponseEntity&lt;&gt;(e.getMessage(), HttpStatus.UNAUTHORIZED);<br>        }<br>    }</pre><h3>Logout Controller</h3><pre>@PostMapping(&quot;/signout&quot;)<br>    public ResponseEntity&lt;?&gt; logoutUser(HttpServletResponse response) {<br>        authenticationService.logoutUser(response);<br>        return new ResponseEntity(&quot;You&#39;ve been signed out!&quot;, HttpStatus.OK);<br>    }</pre><h3>Resource Controller</h3><p>Resource controller contains a public and private resource for testing.</p><pre>@RestController<br>public class ResourceController {<br><br><br>    @GetMapping(&quot;/secret_resource&quot;)<br>    public ResponseEntity&lt;String&gt; secret(){<br>        return new ResponseEntity&lt;&gt;(&quot;You are viewing my secret&quot; , HttpStatus.OK);<br>    }<br>    @GetMapping(&quot;/public_resource&quot;)<br>    public ResponseEntity&lt;String&gt; nosecret(){<br>        // assuming no existing user<br><br>        return new ResponseEntity&lt;&gt;(&quot;You are in public area&quot;, HttpStatus.OK);<br>    }<br>}</pre><p>We have finished all the coding, and now it is time to test out the Rest API with any Api client.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F2e5bfzWMsWo%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fshorts%2F2e5bfzWMsWo%3Ffeature%3Dshare&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F2e5bfzWMsWo%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a8968919e0c2fd34329181fb86989df/href">https://medium.com/media/8a8968919e0c2fd34329181fb86989df/href</a></iframe><p>We have no problem visiting <a href="http://localhost:8080/public_resource">http://localhost:8080/public_resource</a>. However, when visiting <a href="http://localhost:8080/public_resource">http://localhost:8080/secret_resource</a>, we get a 401 Unauthorized . To sign up a new user account at <a href="http://localhost:8080/api/auth/signup">http://localhost:8080/auth/signup</a> We enter a json object with email, name and password. Upon successful signup, we should see a message with 201 Created status. With the valid user credential, we successfully login at <a href="http://localhost:8080/api/auth/login">http://localhost:8080/api/auth/login</a>. We will also see in the JWT cookie in the cookies tab. We can now view the private resource successfully. When we log out at <a href="http://localhost:8080/auth/signout">http://localhost:8080/auth/signout</a>, a signed out message will be shown and if we check the JWT cookie it is now empty.</p><p>Github</p><p><a href="https://github.com/villysiu/SpringSecurityRestAPIJWTDemo">https://github.com/villysiu/SpringSecurityRestAPIJWTDemo.git</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db0ec14e192b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Springboot signup/login Rest API]]></title>
            <link>https://medium.com/@villysiu/java-springboot-signup-login-rest-api-d01b21759ba9?source=rss-8ddd87f6d448------2</link>
            <guid isPermaLink="false">https://medium.com/p/d01b21759ba9</guid>
            <category><![CDATA[spring-security]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[mysql]]></category>
            <dc:creator><![CDATA[Villy Siu]]></dc:creator>
            <pubDate>Sun, 26 Jan 2025 17:49:07 GMT</pubDate>
            <atom:updated>2025-02-05T20:14:13.039Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_zVP1wCt8uplgERuxMk2jQ.png" /></figure><p>In this tutorial, we are building login and sign-up REST API using Spring boot, Spring Security, Spring JPA, and MySQL database.</p><p>The configuration of my system</p><ul><li>Springboot 3.4.2</li><li>Java 17</li><li>JDK 23</li></ul><h3>Create Spring boot application</h3><p>Spring Boot provides a web tool called <a href="https://start.spring.io/"><strong>Spring Initializer</strong></a> to bootstrap an application quickly. Just go to <a href="https://start.spring.io/"><strong>https://start.spring.io/</strong></a> and generate a new spring boot project with Maven or use Intellij Idea.</p><p>Maven dependencies for the project:</p><ul><li>Spring Boot DevTools</li><li>Spring Web</li><li>Spring Security</li><li>Lombak</li><li>JDBC API</li><li>Spring Data JPA</li><li>MySQL</li></ul><h3>Create MySQL database</h3><p>Create a new database, rest_api_user, in MySQL server.</p><h3>Setup connection to database</h3><p>in /src/main/resources/application.properties, added the following text</p><pre>spring.application.name=SpringSecurityRestAPI<br><br>spring.datasource.url = jdbc:mysql://localhost:3306/rest_api_user?useSSL=false&amp;serverTimezone=UTC<br>spring.datasource.username = &lt;-- insert your MySQL username --&gt; <br>spring.datasource.password = &lt;-- insert your MySQL password --&gt;<br><br><br>spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQLDialect<br><br>spring.jpa.hibernate.ddl-auto = update<br><br>logging.level.org.springframework.security=DEBUG</pre><h3>Model/Entity</h3><p>Create the model package in /src/main/java/com.villysiu.springsecurityrestapi . In the newly created model package, we will create the two entities, User.java and Role.java.</p><pre>@Setter<br>@Getter<br>@Entity<br>@Table<br>public class Role {<br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private long id;<br><br>    private String name;<br>}</pre><p>Next the USER entity, we are setting email to be unique for identification.</p><pre>@Data<br>@Entity<br>@Table<br>public class User {<br><br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private long id;<br>    private String name;<br>    private String username;<br><br>    @Column(unique = true)<br>    private String email;<br>    private String password;<br><br>    @ManyToMany(targetEntity = Role.class)<br>    private Set&lt;Role&gt; roles;<br>}</pre><p>To verify the new tables added to the database, we will run the application now and refresh the database in MySQL. We should see the User and Role a table, along with the user_roles table. This is created automatically because we have <a href="https://www.baeldung.com/jpa-many-to-many">many to many</a> relationship between user and role.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*ZP0gasbhNkzZta1oNCC9LQ.png" /></figure><p>In MySQL, add roles “ROLE_ADMIN” and “ROLE_USER”</p><pre>INSERT INTO `rest_api_user`.`role` (`name`) VALUES (&#39;ROLE_ADMIN&#39;);<br>INSERT INTO `rest_api_user`.`role` (`name`) VALUES (&#39;ROLE_USER&#39;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*FcNAsvvrCejoQsEvWAUnAA.png" /></figure><h3>Repository and JPA</h3><p>Next we will create the repository package in /src/main/java/com.villysiu.springsecurityrestapi and create UserRepository.java and RoleRepository.java that extends JpaRepository to interact with the database using the Java Persistence API (JPA). JPA provides built-in methods for basic CRUD operations, ie.save(), findById(), findAll(), and delete() and <strong>Pagination and Sorting, ie.</strong>findAll(Pageable pageable) and findAll(Sort sort).</p><pre>@Repository<br>public interface UserRepository extends JpaRepository&lt;User, Long&gt; {<br>    Optional&lt;User&gt; findByEmail(String email);<br>    Boolean existsByEmail(String email);<br>}</pre><pre>@Repository<br>public interface RoleRepository extends JpaRepository&lt;Role, Long&gt; {<br>    Role findByName(String name);<br>}</pre><p>Note how findByEmail has a return of Optional&lt;User&gt;, according to <a href="https://docs.spring.io/spring-data/jpa/reference/repositories/query-return-types-reference.html">Spring Data JPA docs</a>,</p><blockquote>A Java 8 or Guava Optional. Expects the query method to return one result at most. If no result is found, Optional.empty() or Optional.absent() is returned. More than one result triggers an IncorrectResultSizeDataAccessException.</blockquote><h3>Service</h3><p>we will create the service package in /src/main/java/com.villysiu.springsecurityrestapi and create a CustomUserDetailsService.java which implements the <a href="https://docs.spring.io/spring-security/reference/servlet/authentication/passwords/user-details-service.html">UserDetailsService</a> interface.</p><p>Quoted from this <a href="https://www.geeksforgeeks.org/spring-security-userdetailsservice-and-userdetails-with-example/">article</a>,</p><blockquote>In Spring Security, the UserDetailsService interface is a core component used for loading user-specific data. It is responsible for retrieving user information from a backend data source, such as a database or an external service, and returning an instance of the UserDetails interface.</blockquote><blockquote>The UserDetailsService interface has a single method called <strong><em>loadUserByUsername()</em></strong>, which takes a username as a parameter and returns a fully populated UserDetails object. The UserDetails object represents the authenticated user in the Spring Security framework and contains details such as the user’s username, password, authorities (roles), and additional attributes.</blockquote><p>In our User model, we have setup email to be the unique identifier. When we override loadUserByUsername, we employed findByEmail(email) to find the user in the userRepository. If a user is found, we return a UserDetails object built by an out-of-the-box implementation of org.springframework.security.core.userdetails.User constructor. The UserDetails object represents an authenticated user object</p><pre>@Service<br>public class CustomUserDetailsService implements UserDetailsService {<br>    private final UserRepository userRepository;<br>    public CustomUserDetailsService(UserRepository userRepository) {<br>        this.userRepository = userRepository;<br>    }<br>    @Override<br>    public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {<br>        User user = userRepository.findByEmail(email)<br>                .orElseThrow(() -&gt;<br>                        new UsernameNotFoundException(email + &quot; not found.&quot; ));<br><br>        Set&lt;GrantedAuthority&gt; authorities = user<br>                .getRoles()<br>                .stream()<br>                .map((role) -&gt; new SimpleGrantedAuthority(role.getName())).collect(Collectors.toSet());<br><br>        return new org.springframework.security.core.userdetails.User(<br>                user.getEmail(),<br>                user.getPassword(),<br>                authorities<br>        );<br>    }<br>}</pre><h3>Spring Security Configuration</h3><p>Spring Security provides comprehensive support for authenticating with Username and password. For details, please read the <a href="https://docs.spring.io/spring-security/reference/servlet/architecture.html#servlet-securityfilterchain">Spring Docs</a>.</p><pre>//.csrf(AbstractHttpConfigurer::disable)<br>.csrf(Customizer.withDefaults())<br>.httpBasic(Customizer.withDefaults())<br>.formLogin(Customizer.withDefaults())<br>.authorizeHttpRequests(authorize -&gt; authorize<br>                .anyRequest().authenticated()<br>            );</pre><blockquote>First, the CsrfFilter is invoked to protect against <a href="https://docs.spring.io/spring-security/reference/servlet/exploits/csrf.html">CSRF attacks</a>.</blockquote><blockquote>Second, <a href="https://docs.spring.io/spring-security/reference/servlet/authentication/architecture.html">the authentication filters</a> are invoked to authenticate the request.</blockquote><blockquote>Third, the AuthorizationFilter is invoked to authorize the request.</blockquote><p>Since we are building a REST API, we are going to authenticate the user either in the @Controller or @Service. To do so, we need to publish an AuthenticationManager<em> </em>bean for Custom Authentication, which will be used later in the AuthenticationController.</p><pre>@Bean<br> public AuthenticationManager authenticationManager( UserDetailsService userDetailsService, PasswordEncoder passwordEncoder) {<br>    DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();<br>    authenticationProvider.setUserDetailsService(userDetailsService);<br>    authenticationProvider.setPasswordEncoder(passwordEncoder);<br>  <br>    return new ProviderManager(authenticationProvider);<br> }</pre><pre>.authorizeHttpRequests((auth) -&gt;<br>    auth.requestMatchers(HttpMethod.GET, &quot;public_resource&quot;).permitAll()<br>      .requestMatchers(&quot;/api/auth/**&quot;).permitAll()<br>      .anyRequest().authenticated()<br><br>)</pre><p>In the above code, we allow /public_resource, /api/auth/login, /api/auth/signup to be accessed without authentication. Any other page needs successful authenticaton.</p><p>Exception handling is added here to display a custom message when user is trying to access a private page.</p><p>Session management is added to persist the authenticated user object.</p><p>The completed SecurityConfig:</p><pre><br>@Configuration<br>@EnableWebSecurity<br>public class SecurityConfig {<br><br>    @Bean<br>    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {<br><br>        http<br>                .csrf(AbstractHttpConfigurer::disable)<br>                .exceptionHandling(exceptionHandling -&gt;<br>                                exceptionHandling<br>                                .authenticationEntryPoint(new RestAuthenticationEntryPoint())<br>                )<br>                .authorizeHttpRequests((auth) -&gt;<br>                        auth.requestMatchers(HttpMethod.GET, &quot;public_resource&quot;).permitAll()<br>                                .requestMatchers(&quot;/api/auth/**&quot;).permitAll()<br>                                .anyRequest().authenticated()<br><br>                )<br>                .sessionManagement(s -&gt; s<br>                        .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)<br>                );<br><br>        return http.build();<br>    }<br>    <br>    @Bean<br>    public AuthenticationManager authenticationManager(UserDetailsService userDetailsService, PasswordEncoder passwordEncoder) {<br>        DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();<br>        authenticationProvider.setUserDetailsService(userDetailsService);<br>        authenticationProvider.setPasswordEncoder(passwordEncoder);<br><br>        return new ProviderManager(authenticationProvider);<br>    }<br>    <br>    @Bean<br>    public static PasswordEncoder passwordEncoder(){<br>        return new BCryptPasswordEncoder();<br>    }<br>}</pre><h3>DTO (Data transfer Object)</h3><p>Create the dto package in /src/main/java/com.villysiu.springsecurityrestapi and create LoginRequest.java and SignupRequest.java, which will map to the JSON object in request.</p><pre>@Data<br>public class LoginRequest {<br>    private String email;<br>    private String password;<br>}</pre><pre>@Data<br>public class SignupRequest {<br>    private String name;<br>    private String email;<br>    private String password;<br>}</pre><h3>Controller Layer</h3><p>Create the controller package in /src/main/java/com.villysiu.springsecurityrestapi and create the AuthenticationController.java. There will be the login and signup methods which receives the credentials from @RequestBody and HttpServletRequest for session management.</p><h4>Login</h4><p>A lot is going on behind the scene in the login method. We will break down the method into 3 sections.</p><pre>Authentication authenticationRequest = UsernamePasswordAuthenticationToken.unauthenticated(loginRequest.getEmail(), loginRequest.getPassword());<br>Authentication authenticationResponse = this.authenticationManager.authenticate(authenticationRequest);</pre><p>The credential in LoginRequest is being processed by the DaoAuthenticationProvider. It looks up the UserDetails from the UserDetailsService, then validate the password from the UserDetails with<a href="https://docs.spring.io/spring-security/reference/servlet/authentication/passwords/password-encoder.html#servlet-authentication-password-storage">PasswordEncoder</a>. When successfully authenticated is successful, a UsernamePasswordAuthenticationToken is returned.</p><p>The <a href="https://docs.spring.io/spring-security/reference/servlet/authentication/passwords/dao-authentication-provider.html#servlet-authentication-daoauthenticationprovider">spring docs</a> provides a thorough explanation of how DaoAuthenticationProvider works within Spring Security, read <a href="https://docs.spring.io/spring-security/reference/servlet/authentication/passwords/dao-authentication-provider.html#servlet-authentication-daoauthenticationprovider">here</a>.</p><p>Then we will save the authenticated user in the SecurityContextRepository, so we can easily access the authenticated user.</p><pre>SecurityContextHolder.getContext().setAuthentication(authenticationResponse);</pre><p>To persist the SecurityContext between requests, we are mapping it to &quot;SPRING_SECURITY_CONTEXT” withHttpSession.</p><pre>HttpSession session = request.getSession();<br>session.setAttribute(&quot;SPRING_SECURITY_CONTEXT&quot;, SecurityContextHolder.getContext());</pre><h4>Signup</h4><p>In the registerUser method, we will start by checking if email already existed in the database.</p><pre>if(userRepository.existsByEmail(signupRequest.getEmail())){<br>    return new ResponseEntity&lt;&gt;(&quot;Email already used!&quot;, HttpStatus.BAD_REQUEST);<br>}</pre><p>If email is not already used, we saved the user into our User database.</p><pre>User user = new User();<br>user.setName(signupRequest.getName());<br>user.setEmail(signupRequest.getEmail());<br>user.setPassword(passwordEncoder.encode(signupRequest.getPassword()));<br><br>Role roles = roleRepository.findByName(&quot;ROLE_USER&quot;).get();<br>user.setRoles(Collections.singleton(roles));<br><br>userRepository.save(user);</pre><h4>Logout</h4><p>We used the logout method in <strong>SecurityContextLogoutHandler </strong>class<strong> </strong>to invalidate session and clear the security context.</p><p>After the logout is performed, we removed the attribute <strong>SPRING_SECURITY_CONTEXT</strong> which we set manually during login, and clears the <strong>SecurityContext</strong> from the current thread, effectively logging out the user.</p><p>The completed AuthenticationController :</p><pre>@RestController<br>@RequestMapping(&quot;/api/auth&quot;)<br>public class AuthenticationController {<br><br>    @Autowired<br>    private  AuthenticationManager authenticationManager;<br><br>    @Autowired<br>    private PasswordEncoder passwordEncoder;<br><br>    @Autowired<br>    private UserRepository userRepository;<br><br>    @Autowired<br>    private RoleRepository roleRepository;<br><br>    private final SecurityContextLogoutHandler logoutHandler = new SecurityContextLogoutHandler();<br><br>    @PostMapping(&quot;/login&quot;)<br>    public ResponseEntity&lt;String&gt; login(@RequestBody LoginRequest loginRequest, HttpServletRequest request){<br><br>        Authentication authenticationRequest =<br>                UsernamePasswordAuthenticationToken.unauthenticated(loginRequest.getEmail(), loginRequest.getPassword());<br>        Authentication authenticationResponse = this.authenticationManager.authenticate(authenticationRequest);<br><br>        SecurityContextHolder.getContext().setAuthentication(authenticationResponse);<br><br>        HttpSession session = request.getSession();<br>        session.setAttribute(&quot;SPRING_SECURITY_CONTEXT&quot;, SecurityContextHolder.getContext());<br>        return new ResponseEntity&lt;&gt;(&quot;User signed-in successfully!.&quot;, HttpStatus.OK);<br>    }<br><br>    @PostMapping(&quot;/signup&quot;)<br>    public ResponseEntity&lt;?&gt; registerUser(@RequestBody SignupRequest signupRequest, HttpServletRequest request){<br><br>        if(userRepository.existsByEmail(signupRequest.getEmail())){<br>            return new ResponseEntity&lt;&gt;(&quot;Email already used!&quot;, HttpStatus.BAD_REQUEST);<br>        }<br><br>        User user = new User();<br>        user.setName(signupRequest.getName());<br>        user.setEmail(signupRequest.getEmail());<br>        user.setPassword(passwordEncoder.encode(signupRequest.getPassword()));<br><br>        Role role = roleRepository.findByName(&quot;ROLE_USER&quot;);<br>        user.setRoles(Set.of(role));<br><br>        userRepository.save(user);<br><br>        return new ResponseEntity&lt;&gt;(&quot;User registered successfully&quot;, HttpStatus.OK);<br><br>    }<br>    @PostMapping(&quot;/logout&quot;)<br>    public ResponseEntity&lt;?&gt; logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication){<br>        logoutHandler.logout(request, response, authentication);<br><br>        request.getSession().removeAttribute(&quot;SPRING_SECURITY_CONTEXT&quot;);<br>        request.getSession().invalidate();<br>        SecurityContextHolder.clearContext();<br>        return new ResponseEntity&lt;&gt;(&quot;Logged out successfully&quot;, HttpStatus.OK);<br><br><br>    }<br>}</pre><p>In the controller package, create the ResourceController.java, to hold the private and public end point.</p><pre>@RestController<br>public class ResourceController {<br><br>    @GetMapping(&quot;/secret_resource&quot;)<br>    public ResponseEntity&lt;String&gt; secret(){<br>        return new ResponseEntity&lt;&gt;(&quot;You are viewing my secret&quot; , HttpStatus.OK);<br>    }<br><br>    @GetMapping(&quot;/public_resource&quot;)<br>    public ResponseEntity&lt;String&gt; nosecret(){<br>        // assuming no existing user<br><br>        return new ResponseEntity&lt;&gt;(&quot;You are in public area&quot;, HttpStatus.OK);<br>    }<br>}</pre><p>We have finished all the coding, and now it is time to test out the Rest API with any Api client.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FYtpeNatfwI8%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fshorts%2FYtpeNatfwI8%3Ffeature%3Dshare&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FYtpeNatfwI8%2Fhq2.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/26edd834e54be828eda2b6382b3f1532/href">https://medium.com/media/26edd834e54be828eda2b6382b3f1532/href</a></iframe><p>We have no problem visiting <a href="http://localhost:8080/public_resource">http://localhost:8080/public_resource</a>. However, when visiting <a href="http://localhost:8080/public_resource">http://localhost:8080/private_resource</a>, we are urged to log in. Let’s sign up a new user account at <a href="http://localhost:8080/api/auth/signup">http://localhost:8080/api/auth/signup</a> . We will enter a json object with email, name and password. Upon successful signup, we should see the new user object in mySQL with encrypted password. With the user credential, we are able to login at <a href="http://localhost:8080/api/auth/login">http://localhost:8080/api/auth/login</a>, and access the private resource after logging in successfully.</p><p>This is the end of the tutorial. I hope you will get a thorough understanding of how Spring security works and how to implement a Rest Api. Visit <a href="https://github.com/villysiu/SpringSecurityRestAPIDemo.git">github</a> for the complete code.</p><p><a href="https://github.com/villysiu/SpringSecurityRestAPIDemo.git">https://github.com/villysiu/SpringSecurityRestAPIDemo.git</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d01b21759ba9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to create project and app in django in virtual environment on mac (under development)]]></title>
            <link>https://medium.com/@villysiu/how-to-create-project-and-app-in-django-in-virtual-environment-on-mac-under-development-2835639dc04b?source=rss-8ddd87f6d448------2</link>
            <guid isPermaLink="false">https://medium.com/p/2835639dc04b</guid>
            <dc:creator><![CDATA[Villy Siu]]></dc:creator>
            <pubDate>Mon, 27 Nov 2023 21:43:40 GMT</pubDate>
            <atom:updated>2023-11-27T21:43:40.104Z</atom:updated>
            <content:encoded><![CDATA[<p>first need to have python installed and virtualenv installed.</p><p>Python uses venv as the preferred module to create and manage virtual environments. venv is also included in the Python standard library and does not require any additional installation.</p><p>venv (for Python 3) and virtualenv (for Python 2) allow you to manage separate package installations for different projects.</p><pre>pip3 install virtualenv</pre><p>create a virtual environment in your desired folder. Here I am creating the virtual environment in a folder named ‘coursera_backend’.</p><pre>coursera_backend % python3 -m venv django-venv</pre><pre>//in coursera VSCDOE we use the following to start up virtual environment.<br>~/project$ ~/.local/bin/virtualenv django-venv</pre><p>Once created, a virtual environment must be <em>activated</em>.</p><pre>coursera_backend % source django-venv/bin/activate</pre><p>The shell prompt now has the environment name (.venv) prefixed which indicates that the virtual environment is active</p><pre>(django-venv) coursera_backend %</pre><p>We are now in the virtual environment. Currently there is no Django installed. We can check with the following commant.</p><pre>(django-venv) coursera_backend % python3 -m django --version<br>/Library/Developer/CommandLineTools/usr/bin/python3: No module named django<br>(django-venv) coursera_backend %</pre><p>We will install the version needed as followed:</p><pre>(django-venv) coursera_backend % pip3 install django</pre><p>Now if we checked the version, we will get the following:</p><pre>(django-venv) coursera_backend % python3 -m django --version    <br>4.2.7</pre><p>We are now ready to use django and create our first Django project</p><pre>(django-venv) coursera_backend % django-admin startproject myproject</pre><p>Step inside the project directory by typing a command such as:</p><p>You can check this was successful if the console prompt has a suffix ‘myproject’</p><pre>(django-venv) coursera_backend % cd myproject</pre><p>Create an app ‘myapp’ inside the myproject folder.</p><pre>(django-venv) myproject % python3 manage.py startapp myapp</pre><p>After creating a new app, its a good habit to add it into the INCLUDED_APPS in settings.py in myproject folder</p><pre>&#39;myapp.apps.ModelformappConfig&#39;</pre><p>And in admin.py in teh myapp folder, add</p><p>to start the local Django web server</p><pre>(django-venv) myproject % python3 manage.py runserver</pre><p>Finally, the command prompt will generate some text including a link for the localhost URL such as ```127.0.0.1….```</p><p>To deactivate and leave a virtual environment type deactivate. Do that now.</p><pre>(django-venv) coursera_backend % deactivate<br>coursera_backend %</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2835639dc04b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[input box label]]></title>
            <link>https://medium.com/@villysiu/input-box-label-ffdcceea782f?source=rss-8ddd87f6d448------2</link>
            <guid isPermaLink="false">https://medium.com/p/ffdcceea782f</guid>
            <dc:creator><![CDATA[Villy Siu]]></dc:creator>
            <pubDate>Thu, 02 Feb 2023 05:23:37 GMT</pubDate>
            <atom:updated>2023-02-02T05:23:37.861Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Build Input Box with Movable Placeholder with HTML and CSS</h3><p>Ever wonder how the placeholder in the input box shift to upper left corner when the input box is clicked or contains text ? I am going to show you how to do it in just HTML and CSS in this step-to-step tutorial .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*xYo_H6Wt5mGXIzlvYvMnAw.gif" /></figure><p>First we have the &lt;input&gt; element and &lt;label&gt; element grouped together in a parent &lt;div&gt;.</p><pre>&lt;div&gt;<br>  &lt;input name=&quot;username&quot; <br>         placeholder=&quot;User name&quot;&gt;<br>  &lt;label&gt;User name&lt;/label&gt;<br>&lt;/div&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*lPEHu8z0eKUMylxnh5GNTg.png" /></figure><p>Then we bound the&lt;label&gt; to &lt;input&gt; by adding a for attribute to the &lt;label&gt; .</p><pre>&lt;div&gt;<br>  &lt;input name=&quot;username&quot; <br>         placeholder=&quot;User name&quot;<br>         id=&quot;username&quot;&gt;<br>  &lt;label for=&quot;username&quot;&gt;User name&lt;/label&gt;<br>&lt;/div&gt;</pre><p>Next we will add classes and CSS to the elements. The &lt;label&gt; is supposed to be hidden and only visible when &lt;input&gt; is clicked or containing text. We use the placeholder’s default property to determine the visibility of the &lt;label&gt;, that is, when placeholder is visible, &lt;label&gt; is hidden.</p><pre>&lt;div class=&quot;shift-group&quot;&gt;<br>  &lt;input name=&quot;username&quot; <br>         placeholder=&quot;User name&quot;<br>         id=&quot;username&quot;<br>         class=&quot;shift-input&quot;&gt;<br>  &lt;label for=&quot;username&quot; class=&quot;shift-label&quot;&gt;User name&lt;/label&gt;<br>&lt;/div&gt;</pre><pre>.shift-group {<br>    position: relative;<br>}<br>.shift-input:placeholder-shown + .shift-label  {<br>  visibility:hidden<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*04XKfkH2E2sigTpqszAobg.png" /></figure><p>Now is the cool part. When user clicked in the &lt;input&gt; element or when the &lt;input&gt; box contains text (i.e. placeholder is hidden) , the &lt;label&gt; will become visible. To do so we will set up CSS as followed. The position of the &lt;label&gt; is absolute, its position will depend on the position of the parent &lt;div&gt;.</p><pre>.shift-input:focus + .shift-label,<br>.shift-input + .shift-label {<br>  /* no value in input */<br>  position: absolute;<br>  left: 10px;<br>  top: -10px;<br>  font-size: 12px;<br>  background-color: white;<br>  padding-left: 10px;<br>  padding-right: 10px;<br>  visibility:visible<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*Pg-eY3ZtZUrbXERYbonPxA.gif" /></figure><p>Lastly, we don’t want the placeholder to be there when &lt;input&gt;is clicked. To hide it we add the following to the CSS. The placeholder will be hidden when the &lt;input&gt;is being clicked.</p><pre>.shift-input:focus::placeholder {<br>  visibility:hidden<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*fC2PwGG04dmNpWewKmpsmg.gif" /></figure><p>That’s it. Hope it will help.</p><p>Check out the complete code <a href="https://codepen.io/villysiu/pen/yLqQWPj">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ffdcceea782f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Authenticate User with Devise Gem and Devise JWT in React Application (2/2)]]></title>
            <link>https://medium.com/@villysiu/authenticate-user-with-devise-gem-and-devise-jwt-in-react-application-2-2-98eff841ec88?source=rss-8ddd87f6d448------2</link>
            <guid isPermaLink="false">https://medium.com/p/98eff841ec88</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[jwt-token]]></category>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[devise]]></category>
            <category><![CDATA[fetch-api]]></category>
            <dc:creator><![CDATA[Villy Siu]]></dc:creator>
            <pubDate>Wed, 14 Sep 2022 19:00:44 GMT</pubDate>
            <atom:updated>2022-10-02T01:22:17.634Z</atom:updated>
            <content:encoded><![CDATA[<p>In the previous <a href="https://medium.com/@villysiu/authenticate-user-with-devise-gem-and-devise-jwt-in-react-application-1-2-a869477a2cb3">post</a>, we have built our API in Rails with Devise gem for user authentication, and setup Devise JWT to transmit securely information in JSON object . Now it is time to build the frontend to receive the JWT token. The user interface is simple because I just want to show you how the client communicate with the API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*BcLJgT-gLIj4RvQ2Dd_b1A.gif" /></figure><p>Return to the root folder, react-user-authenitication, and create the react app.</p><pre>cd .. <br>npx create-react-app frontend<br>cd frontend</pre><h4>Configure Port</h4><p>Our API is running in 3000 port. To avoid conflict, we will set the react default port to 3001. Create a new file,.env, in the frontend folder, add the following line.</p><pre># frontend/.env</pre><pre>PORT=3001</pre><p>Now if you run</p><pre>npm start</pre><p>it will start on localhost:3001.</p><h4>Setup User Interface</h4><p>I am going to keep this simple. We will start with App.js. In it we have</p><ul><li>a currUser created with useState hook. It is initialized as null and will be updated after we have succesfully signed up or logged in.</li><li>PrivateText , a compnent to fetch the message.</li><li>User, a component to handle user signup and login, as well as logout upon successful login.</li></ul><pre>#frontend/src/App.js<br>import { useState } from &#39;react&#39;;<br>import &#39;./App.css&#39;;<br>import User from &#39;./components/User&#39;<br>import PrivateText from &#39;./components/PrivateText&#39;</pre><pre>const App=()=&gt;{<br>  const [currUser, setCurrUser]=useState(null);<br>  return (<br>    &lt;div className=&quot;App&quot;&gt;<br>      &lt;User currUser={currUser} setCurrUser={setCurrUser} /&gt;<br>    &lt;/div&gt;<br>  );<br>}<br>export default App;</pre><p>In User.js, we have 3 components, Signup, Login, and Logout. The transmission of the JWT token will happen within the fetch method inside these components.</p><p>We passed in the setCurrUser function into them to update currUser state when we succesfully logged in and logged out.</p><pre># frontend/src/components/User.js<br>import Signup from &quot;./Signup&quot;;<br>import Login from &#39;./Login&#39;<br>import Logout from &#39;./Logout&#39;<br>import { useState } from &quot;react&quot;;<br>const User = ({currUser, setCurrUser}) =&gt; {<br>    const [show, setShow]=useState(true)<br>    if(currUser) <br>        return (<br>            &lt;div&gt;<br>            Hello {currUser.email}<br>            &lt;PrivateText currUser={currUser}/&gt;<br>            &lt;Logout setCurrUser={setCurrUser}/&gt;<br>            &lt;/div&gt;<br>        )<br>    return (<br>        &lt;div&gt;<br>            { show?<br>                &lt;Login setCurrUser={setCurrUser} setShow={setShow}/&gt;  <br>                :<br>                &lt;Signup setCurrUser={setCurrUser}  setShow={setShow} /&gt;<br>            }<br>        &lt;/div&gt;<br>    )<br>}<br>export default User</pre><h4>Signup.js</h4><p>In the Signup.js, after we collected the user email and password in the form, we will wrap the user info in the following format. It is important to do so, because this is how the devise setup to receive.</p><pre>&quot;user&quot;:{ email: data.email, password: data.password }</pre><p>Then we will make a post request to <a href="http://localhost:3000/signup."><em>http://localhost:3000/signup</em>.</a> After devise has successfully created a new user in API, the new user will be signed in (a new session is created). In the client, we will receive a response in JSON object with status 200 success . Along with the response, in the header is the JWT token in Bearer #{token} format.</p><p>We can collect the token by response.headers.get(&quot;Authorization&quot;). Then we will store it in localstorage.</p><pre>localStorage.setItem(&#39;token&#39;,response.headers.get(&quot;Authorization&quot;))</pre><p>currUser will get updated by setCurrUser with the newly created user object.</p><pre>#frontend/src/components/Signup.js</pre><pre>import { useRef } from &quot;react&quot;<br>const Signup=({setCurrUser, setShow})=&gt;{<br>    const formRef = useRef()<br>    const signup=async (userInfo, setCurrUser)=&gt;{<br>        const url=&quot;<a href="http://localhost:3000/signup">http://localhost:3000/signup</a>&quot;<br>        try{<br>            const response=await fetch(url, {<br>                method: &#39;post&#39;,<br>                headers: {<br>                    &quot;content-type&quot;: &#39;application/json&#39;,<br>                    &quot;accept&quot;: &quot;application/json&quot;<br>                },<br>                body: JSON.stringify(userInfo)<br>            }) <br>            const data=await response.json()<br>            if(!response.ok) throw data.error<br>            <strong>localStorage.setItem(&#39;token&#39;, response.headers.get(&quot;Authorization&quot;))</strong><br>            <strong>setCurrUser(data)</strong><br>        } catch (error){<br>            console.log(&quot;error&quot;, error)<br>        }<br>    }<br>    const handleSubmit=e=&gt;{<br>        e.preventDefault()<br>        const formData=new FormData(formRef.current)<br>        const data=Object.fromEntries(formData)<br>        <strong>const userInfo={<br>            &quot;user&quot;:{ email: data.email, password: data.password }<br>        }</strong><br>        signup(userInfo, setCurrUser)<br>        e.target.reset()<br>    }<br>    const handleClick=e=&gt;{<br>        e.preventDefault()<br>        setShow(true)<br>    }<br>    return(<br>        &lt;div&gt;<br>        &lt;form ref={formRef} onSubmit={handleSubmit}&gt;<br>            Email: &lt;input type=&quot;email&quot; name=&#39;email&#39; placeholder=&quot;email&quot; /&gt;<br>            &lt;br/&gt;<br>            Password: &lt;input type=&quot;password&quot; name=&#39;password&#39; placeholder=&quot;password&quot; /&gt;<br>            &lt;br/&gt;<br>            &lt;input type=&#39;submit&#39; value=&quot;Submit&quot; /&gt;<br>        &lt;/form&gt;<br>        &lt;br /&gt;<br>        &lt;div&gt;Already registered, &lt;a href=&quot;#login&quot; onClick={handleClick} &gt;Login&lt;/a&gt; here.&lt;/div&gt;<br>    &lt;/div&gt;<br>    )<br>}<br>export default Signup</pre><h4>Login.js</h4><p>Login is similar to signup. We make a post request to <em>http://localhost:3000/login</em>. User inputs are wrapped in the format devise is designed to receive. Upon successful login, we will store the JWT token in localstorage, and update the user by setCurrUser.</p><pre># frontend/src/components/Login.js<br>import { useRef } from &quot;react&quot;<br>const Login = ({setCurrUser, setShow}) =&gt;{<br>  const formRef=useRef()<br>  const login=async (userInfo, setCurrUser)=&gt;{<br>    const url=&quot;<a href="http://localhost:3000/login">http://localhost:3000/login</a>&quot;<br>    try{<br>        const response=await fetch(url, {<br>            method: &quot;post&quot;,<br>            headers: {<br>                &#39;content-type&#39;: &#39;application/json&#39;,<br>                &#39;accept&#39;: &#39;application/json&#39;<br>            },<br>            body: JSON.stringify(userInfo)<br>        })<br>        const data=await response.json()<br>        if(!response.ok) <br>          throw data.error<br>        <strong>localStorage.setItem(&quot;token&quot;, response.headers.get(&quot;Authorization&quot;))</strong><br>        <strong>setCurrUser(data)</strong>        <br>    }catch(error){<br>       console.log(&quot;error&quot;, error)<br>    }<br>}<br>  const handleSubmit=e=&gt;{<br>    e.preventDefault()<br>      const formData=new FormData(formRef.current)<br>      const data=Object.fromEntries(formData)<br>      <strong>const userInfo={<br>        &quot;user&quot;:{ email: data.email, password: data.password }<br>      }</strong><br>      login(userInfo, setCurrUser)<br>      e.target.reset()<br>  }<br>  const handleClick=e=&gt;{<br>    e.preventDefault()<br>    setShow(false)<br>  }<br>  return(<br>    &lt;div&gt;<br>      &lt;form ref={formRef} onSubmit={handleSubmit}&gt;<br>        Email: &lt;input type=&quot;email&quot; name=&#39;email&#39; placeholder=&quot;email&quot; /&gt;<br>        &lt;br/&gt;<br>        Password: &lt;input type=&quot;password&quot; name=&#39;password&#39; placeholder=&quot;password&quot; /&gt;<br>        &lt;br/&gt;<br>        &lt;input type=&#39;submit&#39; value=&quot;Login&quot; /&gt;<br>      &lt;/form&gt;<br>      &lt;br /&gt;<br>      &lt;div&gt;Not registered yet, &lt;a href=&quot;#signup&quot; onClick={handleClick} &gt;Signup&lt;/a&gt; &lt;/div&gt;<br>    &lt;/div&gt;<br>  )<br>}<br>export default Login</pre><h4>Logout.js</h4><p>In Logout.js, we are sending a “Delete” request to <em>http://localhost:3000/logout</em> for devise to destroy the current session. To do so, we have to be prove that there is a current session going on by sending in the JWT token in the header from localstorage.</p><pre>&quot;authorization&quot;: localStorage.getItem(&quot;token&quot;)</pre><p>Upon successful logout, we will receive a 200 success respone. We will the remove the token from localstoarge and update currUser state to null</p><pre># frontend/src/components/Logout<br>const Logout =({setCurrUser})=&gt;{<br>    const logout=async (setCurrUser)=&gt;{<br>        try {<br>            const response=await fetch(&quot;<a href="http://localhost:3000/logout">http://localhost:3000/logout</a>&quot;,{<br>                method: &quot;delete&quot;,<br>                headers: {<br>                    &quot;content-type&quot;: &quot;application/json&quot;,<br>                    <strong>&quot;authorization&quot;: localStorage.getItem(&quot;token&quot;)</strong><br>                },<br>            })<br>            const data=await response.json()<br>            if(!response.ok) throw data.error</pre><pre>            <strong>localStorage.removeItem(&quot;token&quot;)<br>            setCurrUser(null)</strong><br>        } catch (error) {<br>            console.log(&quot;error&quot;, error)<br>        }<br>    }<br>    const handleClick=e=&gt;{<br>        e.preventDefault()<br>         logout(setCurrUser)<br>    }<br>    return (<br>        &lt;div&gt;<br>            &lt;input type=&quot;button&quot; value=&#39;Logout&#39; onClick={handleClick}/&gt;<br>        &lt;/div&gt;<br>    )<br>}<br>export default Logout</pre><h4>PrivateText.js</h4><p>Now we have covered the user functions. Time to setup the PrivateText component. The private message can only be seen by logged in user. We have a message constant created with useState hook. We will send a GET request to <em>http://localhost:3000/private/test</em>. Like in logout.js, we are sending the JWT token stored in localstorage to the API as well for user authentication. If the token is valid (i.e. user is logged in) and has not expired yet, we will receive a 200 success response, along with the secret message in JSON format. The message will be updated by setMessage and displayed on the screen.</p><pre># frontend/src/components/PrivateText.js<br>import { useState,useEffect } from &quot;react&quot;<br>const PrivateText=({currUser})=&gt;{<br>    const [message, setMessage]=useState(null)<br>    const getText=async ()=&gt;{<br>        try {<br>            const response=await fetch(&quot;<a href="http://localhost:3000/private/test">http://localhost:3000/private/test</a>&quot;, {<br>                method: &quot;get&quot;,<br>                headers: {<br>                    &quot;content-type&quot;: &quot;application/json&quot;,<br>                    <strong>&quot;authorization&quot;: localStorage.getItem(&quot;token&quot;)</strong><br>                }<br>            })<br>            if(!response.ok) throw Error<br>            const data=await response.json()<br>            setMessage(data.message)<br>        }<br>        catch(error){<br>            console.log(&quot;error&quot;, error)<br>            setMessage(null)<br>        }<br>    }<br>    useEffect(()=&gt;{<br>        if(currUser)<br>            getText()<br>    },[currUser])<br>    return(<br>        &lt;div&gt;{message}&lt;/div&gt;<br>    )<br>}<br>export default PrivateText</pre><p>Error handling</p><p>I did not include any error handling on the frontend. Error message is logged in the console.</p><ul><li>If user failed to login, maybe wrong password, we will receive a 401 unauthorized access response.</li><li>During signup, if email already in use, we will receive a 500 (Internal Server Error).</li></ul><p>These errors can be easily displayed on the screen too.</p><h4>The end</h4><p>In this two part tutorial, we have covered setting up API in rails with devise gem and devise-JWT gem, and setting up frontend with React. React communicates with API by sending async request. Ihope you will find this useful. A fully working version in available in github, if you are interested in checking it out.</p><pre><a href="https://github.com/villysiu/react-user-authenication">https://github.com/villysiu/react-user-authenication</a></pre><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98eff841ec88" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Authenticate User with Devise Gem and Devise JWT in React Application (1/2)]]></title>
            <link>https://medium.com/@villysiu/authenticate-user-with-devise-gem-and-devise-jwt-in-react-application-1-2-a869477a2cb3?source=rss-8ddd87f6d448------2</link>
            <guid isPermaLink="false">https://medium.com/p/a869477a2cb3</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[devise]]></category>
            <category><![CDATA[rails]]></category>
            <dc:creator><![CDATA[Villy Siu]]></dc:creator>
            <pubDate>Wed, 14 Sep 2022 06:24:44 GMT</pubDate>
            <atom:updated>2022-09-17T04:28:46.454Z</atom:updated>
            <content:encoded><![CDATA[<p>As I was learning Rails on Ruby, i discovered the power and ease of use of Devise gem in user authentication. I started to look up how to use it with React frontend. I hope this tutorial will help you too.</p><p>Here is the <a href="https://github.com/villysiu/react-user-authenication">github link</a> to the application if you want to check it out youself, or clone it and apply it to your application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*BcLJgT-gLIj4RvQ2Dd_b1A.gif" /></figure><h3>How does this work?</h3><p>According to <a href="https://github.com/waiting-for-dev/devise-jwt#aud_header">Devise-JWT</a> documentation,</p><blockquote>A user authenticates through Devise create session request (for example, using the standard :database_authenticatable module).</blockquote><blockquote>If the authentication succeeds, a JWT token is dispatched to the client in the Authorization response header, with format Bearer #{token} (tokens are also dispatched on a successful sign up).</blockquote><blockquote>The client can use this token to authenticate following requests for the same user, providing it in the Authorization request header, also with format Bearer #{token}</blockquote><blockquote>When the client visits Devise destroy session request, the token is revoked.</blockquote><h3>Creating Rails App</h3><p>To begin, create the a folder called react-user-authenitication. Open the folder in your terminal. Then create a rails application in api mode</p><pre>$ rails new api --api<br>$ cd api</pre><p>In the gem file , uncomment</p><pre># api/Gemfile<br>gem &#39;rack-cors&#39;</pre><p>Since we are in gemfile, add the other gems as well</p><pre>gem &#39;devise&#39;<br>gem &#39;devise-jwt&#39;</pre><pre># &#39;dotenv-rails&#39; is for storing secret key in ENV file<br>gem &#39;dotenv-rails&#39;, groups: [:development, :test]</pre><p>Then, do</p><pre>bundle install</pre><h4>Setup CORS</h4><p>As we are making cross-origin requests, from React frontend to rails API via fetch, we will allow all origins (*) to make request.</p><p>We will also be passing JWT token through headers, so we add “Authorization” to the list of allowed request headers and exposed response headers .</p><p>Next, copy and paste the contents below toconfig/initialzers/cors.rb.</p><pre># api/config/initializers/cors.rb<br>Rails.application.config.middleware.insert_before 0, Rack::Cors do<br>  allow do<br>    origins &#39;<a href="http://localhost:3001&#39;">http://localhost:3001&#39;</a><br>    resource &#39;*&#39;,<br>    headers: [&quot;Authorization&quot;],<br>    expose: [&quot;Authorization&quot;],<br>    methods: [:get, :post, :put, :patch, :delete, :options, :head],<br>    max_age: 600<br>  end<br>end</pre><h4>Create a Private controller</h4><pre>rails generate controller private test</pre><p>Replace private_controller.rb content with the following.</p><pre># api/app/controllers/private_controller.rb<br>class PrivateController &lt; ApplicationController<br>  before_action :authenticate_user!<br>  def test<br>    render json: {<br>      message: &quot;This is a secret message. You are seeing it because you have successfully logged in.&quot; <br>    }<br>  end<br>end</pre><h4>Setting up Devise</h4><pre>rails generate devise:install</pre><p>Defined default url options in your environments files</p><pre># api/config/environments/development.rb<br>config.action_mailer.default_url_options = { host: &#39;localhost&#39;, port: 3000 }</pre><p>To prevent devise from using flash messages which are not presented in Rails api mode. Add this to devise.rb</p><pre># api/config/initializers/devise.rb<br>config.navigational_formats = []</pre><h4>Create Devise User model</h4><pre>rails generate devise User<br>rails db:create<br>rails db:migrate</pre><h4>Configure controllers and routes</h4><p>Create registrations and sessions controllers to handle sign ups and logins.</p><pre>$ rails g devise:controllers users -c registrations sessions</pre><p>Replace contents</p><pre># app/users/registrations_controller.rb<br>class Users::RegistrationsController &lt; Devise::RegistrationsController<br>  respond_to :json<br>  def create<br>    build_resource(sign_up_params)<br>    resource.save<br>    sign_in(resource_name, resource)<br>    render json: resource<br>  end<br>end</pre><pre># app/users/sessions_controller.rb<br>class Users::SessionsController &lt; Devise::SessionsController<br>  respond_to :json<br>  private<br>  def respond_with(resource, _opts = {})<br>    render json: resource<br>  end<br>  def respond_to_on_destroy<br>    render json: { message: &quot;Logged out.&quot; }<br>  end<br>end</pre><h4>Update devise routes.</h4><p>Replace the contents with the following.</p><pre># api/config/routes<br>Rails.application.routes.draw do<br>  get &#39;private/test&#39;<br>  devise_for :users, <br>    path: &#39;&#39;, <br>    path_names: {<br>      sign_in: &#39;login&#39;,<br>      sign_out: &#39;logout&#39;,<br>      registration: &#39;signup&#39;<br>    },<br>    controllers: {<br>      sessions: &#39;users/sessions&#39;,<br>      registrations: &#39;users/registrations&#39;<br>    }<br>end</pre><h4>Secret key configuration</h4><p>Secret key is used to create JWT token. Generate secret key by running</p><pre>bundle exec rake secret</pre><p>Create a <em>.env</em> file in the project root and add the secret key inside.</p><pre># api/.env<br>DEVISE_JWT_SECRET_KEY=&lt;your_rake_secret&gt;</pre><p>Note: Add .env into the gitignore file if pushing to GitHub.</p><h4>Configure devise-jwt</h4><p>Add the following to devise.rb</p><pre># api/config/initializers/devise.rb</pre><pre>config.jwt do |jwt|<br>    jwt.secret = ENV[&#39;DEVISE_JWT_SECRET_KEY&#39;]<br>    jwt.dispatch_requests = [<br>      [&#39;POST&#39;, %r{^/login$}],<br>    ]<br>    jwt.revocation_requests = [<br>      [&#39;DELETE&#39;, %r{^/logout$}]<br>    ]<br>    jwt.expiration_time = 5.minutes.to_i<br>  end</pre><p>If the frontend request to login suceeds, a new JWT token, generated based on the secret key, is dispatched to the client in the Authorization response header, in Bearer #{token} . On a successful sign up, a sign in call is made in the controller. Frontend will receive JWT token in the header too.</p><p>If a logout request is made, upon successful destroy, the token will be revoked.</p><p><strong>Revocation strategies</strong></p><p>Devise-jwt comes with three revocation strategies. We will use Denylist. According to the <a href="https://github.com/waiting-for-dev/devise-jwt#aud_header">devise-jwt </a>documentation,</p><blockquote>In this strategy, a database table is used as a list of revoked JWT tokens. The jticlaim, which uniquely identifies a token, is persisted. The exp claim is also stored to allow the clean-up of stale tokens.</blockquote><p>Create the denylist table</p><pre>rails generate migration create_jwt_denylist</pre><p>Replace the content with the following:</p><pre># api/db/migrate/[date]_create_jwt_denylist.rb<br>def change<br>  create_table :jwt_denylist do |t|<br>    t.string :jti, null: false<br>    t.datetime :exp, null: false<br>  end<br>  add_index :jwt_denylist, :jti<br>end</pre><p>Then run</p><pre>rails db:migrate</pre><p>Create a JwtDenylist model and replace the content to:</p><pre># api/app/models/jwt_denylist.rb<br>class JwtDenylist &lt; ApplicationRecord<br>  include Devise::JWT::RevocationStrategies::Denylist</pre><pre>  self.table_name = &#39;jwt_denylist&#39;<br>end</pre><p>Update user model to use JWT token.</p><pre># api/app/models/user.rb<br>class User &lt; ApplicationRecord<br>  devise :database_authenticatable, :registerable,<br>         :jwt_authenticatable, jwt_revocation_strategy: JwtDenylist<br>end</pre><p>Now if we run</p><pre>rails s</pre><p>and visit</p><pre>http://localhost:3000/private/test</pre><p>You will get the message “You need to sign in or sign up before continuing.” Our backend is completed, we will discuss the React frontend in the next post.</p><p>Next we will work on the react frontend, see you in <a href="https://medium.com/@villysiu/authenticate-user-with-devise-gem-and-devise-jwt-in-react-application-2-2-98eff841ec88">part 2</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a869477a2cb3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Time Complexity]]></title>
            <link>https://medium.com/@villysiu/time-complexity-126025f0f447?source=rss-8ddd87f6d448------2</link>
            <guid isPermaLink="false">https://medium.com/p/126025f0f447</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[big-o-notation]]></category>
            <category><![CDATA[time-complexity]]></category>
            <dc:creator><![CDATA[Villy Siu]]></dc:creator>
            <pubDate>Mon, 12 Sep 2022 15:44:48 GMT</pubDate>
            <atom:updated>2022-09-12T15:44:48.240Z</atom:updated>
            <content:encoded><![CDATA[<p>What is time complexity</p><p>As we get more experience with coding, we will want to know how we can make our code runs more efficiently. We can do this by finding the time and space complexity. We are only discussing time complexity in this article. Time complexity is the number of time a statement is being executed as element size grows (eventually to Infinity).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*EJ8GptIPuMbgzvoAbn4E3g.jpeg" /></figure><p>image credit<br>https://www.freecodecamp.org/news/content/images/2021/06/1_KfZYFUT2OKfjekJlCeYvuQ.jpeg</p><p>The basic time complexity are O(1), O(log n), and O(n).</p><p>O(n*log n), O(n²) and O(mn) are calculated based on the above 3 time complexity.</p><p>There are also O(2^n) and O(n!) which could be lead to Infinity, so we are not discussing it here.</p><p><strong>O(1)</strong></p><pre>let x=0<br>let temp=x<br>let y=x+1<br>return temp<br>for(let x=0, i=0;i&lt;3;i++){<br> x++<br>}</pre><p>Time complexity does not change. ie, constant amount of time is used to execute each line of code.</p><p><strong>O(n)</strong></p><pre>for(let i=0;i&lt;n;i++)<br> x++</pre><p>Time complexity chnages according to n. ie, linear amount of time is used to execute the code in the for loop.<br>Time complexity for searching an item in an array from position 0 is O(n). We only consider the worst case, which means we check every item in teh array from begining to end.</p><p><strong>O(log n)</strong></p><pre>let i=1<br>while(i&lt;n)<br>    i*=2</pre><p>In the example, i is doubled and getting closer to n in every loop. The number of loops to reach n is x=log2(n) Time complexity of binary search is O(log n). we repeatedly divided the sorted array in half and look for which gorup the target will be. Its more efficient than checking every item in the array.</p><p>It seems straight forward to calculate time complexity in the above examples when the code is short. In reality our code is way longer and complex. We are not displaying all the time complexity with a long strand of every operation. We only count the dormant ones and ignore constants and lower order ones. <br>Thus O(1) operations within for or while loop are often ignored. When we calculated time, we only considered worst case scenario in the loop.</p><p><strong>O(n log n)</strong></p><pre>for(let i=0;i&lt;n;i++){<br> let i=1<br> while(i&lt;n)<br> i*=2<br>}</pre><p>Here we have a while loop (O(log n)) being run n time, thus we have O(n * O(log n * O(1))) = O(n log n)</p><p><strong>O(n²)</strong></p><pre>for(let r=0;r&lt;n;r++){<br> for(let c=0;c&lt;n;c++){<br> matrix[r][c]=1<br> }<br>}</pre><p>In this 2D array we have a for loop within a for loop with same number of cycel, ie O(n * O(n * O(1))) = O(n²)</p><p><strong>O(mn)</strong><br>In the case the 2d array with diffenet sizes</p><pre>for(let r=0;r&lt;m;r++){<br>  for(let c=0;c&lt;n;c++){<br>    matrix[r][c]=1<br>  }<br>}</pre><p>We still have a for loop within a for loop, but this time the number of cycles in worst case are different. ie O(m * O(n * O(1))) = O(mn)</p><p>Here is a more complicated example:</p><pre>for(let j=0;j&lt; 3;j++){ //O(1)<br> for(let i=0;i&lt;n;i++){ //O(n)<br>   let i=1<br>   while(i&lt;n) //O(logn)<br>     i*=2<br>   <br>  }<br>}</pre><p>O(3*O(n * O(log n *(O(1))))) is shorten to O(nlogn)<br>this process of ignoring thh lower term is known as Big O notation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=126025f0f447" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>